70 lines
2.5 KiB
Transact-SQL
70 lines
2.5 KiB
Transact-SQL
/*
|
|
AllowanceTypeToAllowanceDeduction_DB_Changes.sql
|
|
|
|
Moves the Allowance Type (EnumAllowanceType: 0 Non_Gross, 1 HouseRent, 2 Medical, 3 Conveynce, 4 Utilities_Other)
|
|
from the parameter (ADPARAMETERBASIC.allowanceType) to the allowance head
|
|
(AllowanceDeduction.AllowanceType).
|
|
|
|
Run this BEFORE deploying the matching code: the new code writes AllowanceDeduction.AllowanceType
|
|
and no longer writes ADPARAMETERBASIC.allowanceType.
|
|
|
|
Run order (inside this script): 1 add column -> 2 copy existing values -> 3 drop old column.
|
|
Step 2 must run before step 3, or the values are lost.
|
|
Every step is guarded, so the script is safe to run more than once.
|
|
*/
|
|
|
|
SET NOCOUNT ON;
|
|
GO
|
|
|
|
/* 1. Add AllowanceDeduction.AllowanceType */
|
|
IF COL_LENGTH('dbo.AllowanceDeduction', 'AllowanceType') IS NULL
|
|
BEGIN
|
|
ALTER TABLE dbo.AllowanceDeduction
|
|
ADD AllowanceType INT NOT NULL
|
|
CONSTRAINT DF_AllowanceDeduction_AllowanceType DEFAULT (0);
|
|
PRINT 'Added AllowanceDeduction.AllowanceType';
|
|
END
|
|
GO
|
|
|
|
/* 2. Copy the values already set on the parameters onto their allowance head.
|
|
An allowance with several parameters takes the highest non-zero value. */
|
|
IF COL_LENGTH('dbo.ADPARAMETERBASIC', 'allowanceType') IS NOT NULL
|
|
BEGIN
|
|
EXEC sp_executesql N'
|
|
UPDATE AD
|
|
SET AD.AllowanceType = X.AllowanceType
|
|
FROM dbo.AllowanceDeduction AD
|
|
JOIN (SELECT AllowDeductID, MAX(ISNULL(allowanceType, 0)) AS AllowanceType
|
|
FROM dbo.ADPARAMETERBASIC
|
|
GROUP BY AllowDeductID) X
|
|
ON X.AllowDeductID = AD.ALLOWDEDUCTID
|
|
WHERE AD.AllowanceType = 0
|
|
AND X.AllowanceType <> 0;';
|
|
PRINT 'Copied ADPARAMETERBASIC.allowanceType to AllowanceDeduction.AllowanceType';
|
|
END
|
|
GO
|
|
|
|
/* 3. Drop ADPARAMETERBASIC.allowanceType (its default constraint first, if any) */
|
|
IF COL_LENGTH('dbo.ADPARAMETERBASIC', 'allowanceType') IS NOT NULL
|
|
BEGIN
|
|
DECLARE @df SYSNAME, @sql NVARCHAR(MAX);
|
|
|
|
SELECT @df = dc.name
|
|
FROM sys.default_constraints dc
|
|
JOIN sys.columns c
|
|
ON c.object_id = dc.parent_object_id
|
|
AND c.column_id = dc.parent_column_id
|
|
WHERE dc.parent_object_id = OBJECT_ID('dbo.ADPARAMETERBASIC')
|
|
AND c.name = 'allowanceType';
|
|
|
|
IF @df IS NOT NULL
|
|
BEGIN
|
|
SET @sql = N'ALTER TABLE dbo.ADPARAMETERBASIC DROP CONSTRAINT ' + QUOTENAME(@df) + N';';
|
|
EXEC sp_executesql @sql;
|
|
END
|
|
|
|
ALTER TABLE dbo.ADPARAMETERBASIC DROP COLUMN allowanceType;
|
|
PRINT 'Dropped ADPARAMETERBASIC.allowanceType';
|
|
END
|
|
GO
|