数据库方案,自动增量

时间:2017-04-07 11:39:48

标签: sql-server

数据库问题在这里。 是否可以对二级或三级ID进行自动增量? 我需要制作基于版本的版本,所以想象一下:

ID  Phrase  PhraseID    PhraseVersion
1   ""      1           1
2   ""      1           2
3   ""      1           3
4   ""      2           1

PhraseID在添加到数据库时可以是相同的数字。 如果PhraseID存在,我希望PhraseVersion自动增加数量。 如果PhraseID不存在,我希望PhraseVersion重新开始,从1开始计算。

我有可能吗?

2 个答案:

答案 0 :(得分:2)

我会使用PhraseVersion的计算列,这将使得与PhraseIDId相同的行数小于或等于当前行。

为此,您需要创建一个UDF来计算PhraseVersion:

CREATE FUNCTION dbo.GetPhraseVersion (
    @PhraseId int,
    @id int
)
RETURNS INT
AS
BEGIN
    RETURN (
        SELECT COUNT(*) 
        FROM T 
        WHERE PhraseId = @PhraseId 
        AND Id <= @id
    )
END
GO

然后,使用计算列创建表:

CREATE TABLE T
(
    id int identity(1,1),
    PhraseId int,
    PhraseVersion as dbo.GetPhraseVersion(PhraseId, id)
)

GO

现在进行测试 - 插入4条记录:

INSERT INTO T (PhraseId) VALUES(1),(1),(1),(2)

选择:

SELECT *
FROM T

结果:

id  PhraseId    PhraseVersion
1   1           1
2   1           2
3   1           3
4   2           1

You can see a live demo on rextester.

答案 1 :(得分:0)

这可以通过表上的插入触发器来完成:

CREATE TABLE Phrases (
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY, 
    PhraseID INT NOT NULL DEFAULT(0), 
    PhraseVersion INT NOT NULL DEFAULT(0))
GO

-- ==========================================================================================
-- Author:         Donna Landy
-- Create Date:    21 Nov 2019
-- Purpose:        To populate the PhraseVersion column (subordinate numeric key) on Insert
-- Note:           Must cater for >1 row being inserted when this trigger is called
-- Strategy:       Construct a temp table with the rows we need to consider, then update one row at a time
-- ==========================================================================================

CREATE TRIGGER Phrases_Insert ON Phrases AFTER INSERT
AS
BEGIN

    DECLARE @ID INT
    DECLARE @PhraseID INT
    DECLARE @PhraseVersion INT

    DECLARE @i INT
    DECLARE @iMax INT

    -- Create and populate temp table
    IF OBJECT_ID('tempdb..#phrases', 'U') IS NOT NULL DROP TABLE #phrases
    CREATE TABLE #phrases (i INT IDENTITY(1,1) PRIMARY KEY, ID INT, PhraseID INT)
    INSERT INTO #phrases (ID, PhraseID) SELECT ID, PhraseID FROM inserted

    -- Scan temp table
    SET @i=1
    SELECT @iMax=MAX(i) FROM #phrases

    WHILE @i <= @iMax BEGIN

        -- Fetch PhraseID & PhraseVersion for the row we are going to update
        SELECT @ID=ID, @PhraseID=PhraseID FROM #phrases WHERE i=@i

        -- Find the highest current Ref
        SELECT @PhraseVersion=ISNULL(MAX(PhraseVersion),0) FROM Phrases WHERE PhraseID=@PhraseID

        -- Update the row 
        UPDATE Phrases SET PhraseVersion=@PhraseVersion+1 WHERE ID=@ID 

        -- Increment loop counter
        SET @i+=1

    END

    -- Remove temp table
    IF OBJECT_ID('tempdb..#phrases', 'U') IS NOT NULL DROP TABLE #phrases

END
GO