在表上创建主键使用其他表中的值

时间:2019-03-16 18:21:01

标签: sql-server tsql

我需要创建并能够编辑将如何在表上创建ID。 假设我有两个表:

CREATE TABLE [dbo].[Consecutives]
(
        [Consecutives_ID] [INT] IDENTITY(1,1) NOT NULL,
        [Name] [VARCHAR](100) NULL,
        [Value] [INT] NOT NULL,
        [Prefix] [VARCHAR] NOT NULL,
        CONSTRAINT PK_Consecutives PRIMARY KEY (Consecutives_ID)
);

CREATE TABLE [dbo].[Users]
(
        [User_ID] [INT] NOT NULL PRIMARY KEY,
        [LogIn] [VARCHAR](100) NULL,
        [Pass] [VARCHAR](100) NOT NULL,
        CONSTRAINT PK_Users PRIMARY KEY (User_ID)
);

是否可以通过使用连续表上的前缀和值数据在 Users 表上创建主键,并在使用该值后对其进行递增?(通过约束?只能通过存储过程来实现?)

例如,在“连续”表中插入以下内容:

INSERT INTO [dbo].[Consecutives] ([Name], [Value], [Prefix]) 
VALUES (Users, 50, "USR-")

然后我尝试创建一个新用户,生成的USER_ID值将为“ USR-50”,并且“连续”表的值将更新为“ 51”

1 个答案:

答案 0 :(得分:0)

DROP TRIGGER IF EXISTS [dbo].[primary_key]
GO

DROP TABLE IF EXISTS [dbo].[Users]
GO

DROP TABLE IF EXISTS [dbo].[Consecutives]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Consecutives](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](100) NULL,
    [Value] [int] NOT NULL,
    [Prefix] [varchar](100) NOT NULL,
 CONSTRAINT [PK_Consecutives] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
    [ID] [varchar](50) NOT NULL,
    [LogIn] [varchar](100) NULL,
    [Pass] [varchar](100) NOT NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[primary_key] 
   ON  [dbo].[Users]
   AFTER INSERT
AS 
BEGIN
    SET NOCOUNT ON;
    DECLARE @id varchar(50);
    DECLARE @nextid int;
    SELECT @id = (SELECT TOP 1 Prefix + cast(Value as varchar) FROM Consecutives);
    SELECT @nextid = (SELECT TOP 1 Value + 1 FROM Consecutives);

    UPDATE Users SET ID = @id WHERE ID = (SELECT ID FROM inserted);
    UPDATE Consecutives SET Value = @nextid;

END
GO
ALTER TABLE [dbo].[Users] ENABLE TRIGGER [primary_key]
GO

INSERT INTO Consecutives ([Name], [Value], [Prefix]) 
VALUES ('Users', 50, 'USR-');

INSERT INTO Users([ID],[LogIn],[Pass])
VALUES('one','login1','pass1');

INSERT INTO Users([ID],[LogIn],[Pass])
VALUES('two','login2','pass2');

INSERT INTO Users([ID],[LogIn],[Pass])
VALUES('three','login3','pass3');

SELECT * FROM Users;
SELECT * FROM Consecutives;