当新值发现重复时,我需要触发以增加第二个数字。
对于Instance,我有一个10位数的唯一字段。我想当有人插入相同的号码时,它会增加第二个左手数字,如0100012345.我怎么能这样做?谢谢。
FirstName LastName代码 Houssam Salim 0100012345为0200012345
答案 0 :(得分:0)
试试这个
我找到了一个解决方案,而不是关闭触发器
' / * CREATE TABLE [Employee1] ( [id] VARCHAR(20)PRIMARY KEY, [名称] VARCHAR(50) )
创建TRIGGER AutoIncrement_Trigger ON [员工1] 而不是INSERT 如 开始 DECLARE @ch CHAR DECLARE @num INT
IF EXISTS (SELECT 1
FROM Employee1 e
JOIN inserted i
ON i.id = e.id)
BEGIN
SET @num=(SELECT max(CONVERT(INT, substring(e.id, 1, 2))) + 1
FROM employee1 e
JOIN inserted i
ON substring(e.id, 3, len(e.id)) = substring(i.id, 3, len(i.id)))
INSERT INTO [Employee1]
(id,
name)
SELECT '0' + CONVERT(VARCHAR(10), @num)
+ substring(i.id, 3, len(i.id)),
e.name
FROM Employee1 e
JOIN inserted i
ON i.id = e.id
END
ELSE
BEGIN
INSERT INTO [Employee1]
(id,
name)
SELECT inserted.id,
inserted.name
FROM inserted
END
END * / 插入[Employee1] 价值观(' 0100012345', '约翰&#39)
SELECT * 来自[Employee1]
INSERT INTO [Employee1] 价值观(' 0100012345', '约翰&#39)
SELECT * 来自[Employee1]
'