BdR
BdR

Reputation: 3058

Column with DEFAULT function, pass parameter or determine insert values?

In MS-SQL Server, is it possible to pass a parameter to a DEFAULT function, or somehow base the DEFAULT value on the values inserted in the record?

You can assign a function as a DEFAULT value for a column in MS-SQL Server. Using this, I'm trying to achieve the following. For a table with study ids and patient ids, I want to automatically assign a new patient number within that study.

CREATE TABLE [dbo].[PATIENT_STUDY](
    [PatientStudyID] [int] IDENTITY(1,1) NOT NULL,
    [PatientID] [int] NOT NULL,
    [StudyID] [int] NOT NULL,
    [PatientCode] [varchar(30)] NULL,
    [ActiveParticipant] [tinyint] NULL -- 1=yes
)

-- set function as DEFAULT for column PatientCode
ALTER TABLE PATIENT_STUDY
ADD CONSTRAINT 
    DF_PATIENT_STUDY_CODE
    DEFAULT([dbo].[fn_Generate_PatientCode]())
    FOR PatientCode

GO

So for example when a patient is added to STID=67 (for example with studycode "012"), and the last patientcode for that study was "012-00024", then the next patientcode should be "012-00025".

ID  PatientID StudyID PatientCode Active
--- --------- ------- ----------- -------
101 92        65      '009-00031' 1
102 93        66      '010-00018' 1
103 94        67      '012-00023' 1
104 95        67      '012-00024' 1

I know this can be achieved with a INSERT trigger, but I was wondering if it's also possible with DEFAULT, as this is a somewhat cleaner solution, easier to maintain.

I've tried the following.

CREATE FUNCTION [dbo].[fn_Generate_PatientCode]()
RETURNS VARCHAR(10) -- for example "012-00345"
AS 
BEGIN
    -- variables
    DECLARE @Code_next INT
    DECLARE @Code_new VARCHAR(10)

    -- find values of current record, how?
    DECLARE @STID INT
    SET @STID = ?? -- How to determine current record? <--------------------- !!

    -- determine the studycode, example '023-00456' -> '023'
    SET @StudyCode = (SELECT StudyCode FROM Study WHERE StudyID = @STID)

    -- determine max study nr per study, example '123-00456' -> 456
    SET @Code_next = (SELECT MAX(SUBSTRING(PatientCode, 5, 5))
                FROM PATIENT_STUDY
                WHERE IsNumeric(SUBSTRING(PatientCode, 5, 5)) = 1
                AND StudyID = @STID
                ) + 1 -- get next number

    -- check if first patient in this study
    IF (@Code_next is null) 
    BEGIN
        SET @Code_next = 1
    END

    -- prefix with zeroes if needed
    SET @Code_new = @Code_next
    WHILE (LEN(@Code_new) < 5) SET @Code_new = '0' + @Code_new

    -- build new patient code, example '012-00025'
    SET @Code_new = @StudyCode + '-' + @Code_new

    -- return value
    RETURN @Code_new
END

Upvotes: 0

Views: 2054

Answers (1)

Giorgos Altanis
Giorgos Altanis

Reputation: 2760

No, I don't think you can do it without a trigger.

Upvotes: 2

Related Questions