HRM-10/ADParameterBasicUserIDNullable_DB_Changes.sql

56 lines
2.3 KiB
MySQL
Raw Normal View History

2026-11-18 14:51:31 +06:00
/*
ADParameterBasicUserIDNullable_DB_Changes.sql
Why:
ADParameterDA.Insert (HRM.DA/DA/AllowDeduct/ADParameterDA.cs) wrote a hard-coded 1 into
dbo.ADPARAMETERBASIC.USERID. On databases with no USERS.USERID = 1 (MasterProjectDBUATBRAC)
every allowance parameter save fails on FK_ADPARAMETERBASIC_USERS. The insert will stop
writing USERID, so the column has to accept NULL.
What:
Makes dbo.ADPARAMETERBASIC.USERID int NULL. The foreign key FK_ADPARAMETERBASIC_USERS is kept:
it is dropped only for the ALTER and re-created on USERS(USERID). A NULL value is allowed by the
foreign key; any value written stays checked.
Run order:
Run BEFORE deploying the code that removes USERID from the insert (a NOT NULL column with no
value in the INSERT fails). Re-runnable: does nothing when the column is already nullable.
*/
IF COL_LENGTH('dbo.ADPARAMETERBASIC', 'USERID') IS NOT NULL
AND COLUMNPROPERTY(OBJECT_ID('dbo.ADPARAMETERBASIC'), 'USERID', 'AllowsNull') = 0
BEGIN
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.FK_ADPARAMETERBASIC_USERS', 'F') IS NOT NULL
ALTER TABLE dbo.ADPARAMETERBASIC DROP CONSTRAINT FK_ADPARAMETERBASIC_USERS;
ALTER TABLE dbo.ADPARAMETERBASIC ALTER COLUMN USERID int NULL;
ALTER TABLE dbo.ADPARAMETERBASIC WITH NOCHECK
ADD CONSTRAINT FK_ADPARAMETERBASIC_USERS FOREIGN KEY (USERID) REFERENCES dbo.USERS (USERID);
COMMIT TRANSACTION;
PRINT 'dbo.ADPARAMETERBASIC.USERID is now NULL-able (FK_ADPARAMETERBASIC_USERS re-created).';
END
ELSE
PRINT 'dbo.ADPARAMETERBASIC.USERID is already NULL-able (or missing) - nothing to do.';
GO
-- Part 2: USERID carries DEFAULT ((1)), so an INSERT that leaves the column out still writes 1 and
-- fails the same foreign key. Drop that default so the column stays NULL.
DECLARE @dfName sysname;
SELECT @dfName = 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 = 'USERID';
IF @dfName IS NOT NULL
BEGIN
EXEC ('ALTER TABLE dbo.ADPARAMETERBASIC DROP CONSTRAINT ' + @dfName);
PRINT 'Default constraint ' + @dfName + ' on dbo.ADPARAMETERBASIC.USERID dropped.';
END
ELSE
PRINT 'dbo.ADPARAMETERBASIC.USERID has no default - nothing to do.';
GO