我正在添加三个字段的计算列。它将是一个VARCHAR字段。我需要指定计算列的最大长度。我们如何指定。
ALTER TABLE [MyTable] ADD CustomNumber AS [PGM]+'-'+[GRP]+'-'+[PGMGRPSEQ]
有没有办法可以限制它?如果长度超过10个字符,我需要引发错误
答案 0 :(得分:4)
单程
CREATE TABLE [MyTable]
(
[PGM] VARCHAR(50),
[GRP] VARCHAR(50),
[PGMGRPSEQ] VARCHAR(50),
CustomNumber AS [PGM]+'-'+[GRP]+'-'+[PGMGRPSEQ] PERSISTED CHECK (LEN(CustomNumber) <= 10)
)
或者,如果您不想保留计算列,只需添加一个重复表达式的检查约束。
CREATE TABLE [MyTable]
(
[PGM] VARCHAR(50),
[GRP] VARCHAR(50),
[PGMGRPSEQ] VARCHAR(50),
CustomNumber AS [PGM]+'-'+[GRP]+'-'+[PGMGRPSEQ],
CHECK (LEN([PGM]+'-'+[GRP]+'-'+[PGMGRPSEQ] ) <= 10)
)
答案 1 :(得分:0)
假设,最大长度为100,则:
ALTER TABLE [MyTable] ADD CustomNumber
AS Ltrim(Substring([PGM]+'-'+[GRP]+'-'+[PGMGRPSEQ] + Space(100), 1, 100))
答案 2 :(得分:0)
试试这个:
CREATE TABLE [MyTable]
(
[PGM] VARCHAR(50),
[GRP] VARCHAR(50),
[PGMGRPSEQ] VARCHAR(50)
)
ALTER TABLE [MyTable] ADD CustomNumber AS [PGM]+'-'+[GRP]+'-'+[PGMGRPSEQ] PERSISTED
GO
ALTER TABLE [MyTable]
ADD CONSTRAINT [MaxLenLimit] CHECK (LEN([CustomNumber]) <= 100)