在SQL Server中基于多个字段通过自动序列创建触发器

我正在尝试为SQL Server中依赖于多个字段的UniqueID字段创建自动序列触发器。例如,我有一个名为animals的表,其中有列Species,Sex,UniqueID。我正在尝试为何时输入物种和性别创建触发器,该ID是根据该物种和性别的最后一个序列号自动填充的。需要看起来像DeerM0001。到目前为止,这是我所拥有的,但是它不起作用。

CREATE TRIGGER tr_animalID
ON  animal
AFTER INSERT,UPDATE
AS 
BEGIN
    SET NOCOUNT ON;

    DeclARE @ID varchar(8)
    SET @ID = (SELECT max(Species) FROM animal);

    UPDATE animal
    SET UniqueID = concat(Species,Sex) +0001 
    WHERE UniqueID = @ID;
END
GO
NOKIA3650 回答:在SQL Server中基于多个字段通过自动序列创建触发器

这里是一个使用带有标识的计算列的例子。我建议将Species作为字符串存储不是一个好计划。您应该有一个Species表,以避免一遍又一遍地输入名称。它可以防止输入错误,还可以轻松支持多种语言。另外,请注意,使用0进行右填充就像您对系统有内置限制。最终它将用完数字。

create table Animal
(
    AnimalID int identity,Species varchar(10) --this should really be a foreign key instead of the name over and over,Sex char(1) not null,UniqueID as Concat(Species,Sex) + right(replicate('0',8) + convert(varchar(10),AnimalID),6) --this pads the identity value to a max length of 6.
)

insert Animal values
('Deer','M'),('Deer','F'),('Goat','M')

select *
from Animal

如果您真的想使用序列,则基本语法非常简单。

create sequence MySequence as int start with 1 increment by 1

select next value for MySequence

您还可以找到其他成千上万个示例here

本文链接:https://www.f2er.com/3156651.html

大家都在问