具有 DEFAULT 函数、传递参数或确定插入值的列?

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

在 MS-SQL 服务器中,是否可以将参数传递给 DEFAULT 函数,或者以某种方式将 DEFAULT 值基于记录中插入的值?

您可以将函数指定为 MS-SQL 服务器中列的默认值。使用它,我试图实现以下目标。对于具有研究 ID 和患者 ID 的 table,我想在该研究中自动分配一个新的患者编号。

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

例如,当患者被添加到 STID=67(例如研究代码为“012”)时,该研究的最后一个患者代码为“012-00024”,那么下一个患者代码应为“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

我知道这可以通过 INSERT 触发器来实现,但我想知道是否也可以使用 DEFAULT,因为这是一种更简洁的解决方案,更易于维护。

我尝试了以下方法。

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

不,我认为没有触发器你做不到。