【发布时间】:2017-07-19 09:36:58
【问题描述】:
在 MS-SQL Server 中,是否可以将参数传递给 DEFAULT 函数,或者以某种方式将 DEFAULT 值基于插入记录中的值?
您可以将函数指定为 MS-SQL Server 中列的默认值。使用它,我试图实现以下目标。对于包含研究 ID 和患者 ID 的表格,我想在该研究中自动分配一个新的患者编号。
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
【问题讨论】:
-
如果您可以按顺序进行分配,我建议您使用标识列或序列。您可以将 012-00025 构建为计算列。
标签: sql-server function sql-server-2008 default-value