在将记录插入sql server时生成带条件的自定义id

时间:2016-07-12 07:28:45

标签: sql sql-server database tsql uniqueidentifier

如何根据条件插入记录时生成自定义ID?例如,我有一个donor database program,可以接受来自non-alumnialumni的捐款。校友的自定义ID应从A00001开始,非校友的自定义ID为N00001。值得注意的是,将要插入的记录将来自另一个记录来自excel文件的表。

任何帮助或澄清将不胜感激。

1 个答案:

答案 0 :(得分:0)

也许这样的事情?

 DECLARE @Table TABLE ( ID VARCHAR(20) );

-- Non alumni
INSERT  INTO @Table
        ( ID )
VALUES  ( 'N00011' )

INSERT  INTO @Table
        ( ID )
VALUES  ( 'N00012' )

INSERT  INTO @Table
        ( ID )
VALUES  ( 'N00013' )

-- Alumni
INSERT  INTO @Table
        ( ID )
VALUES  ( 'A00011' )

INSERT  INTO @Table
        ( ID )
VALUES  ( 'A00012' )

INSERT  INTO @Table
        ( ID )
VALUES  ( 'A00013' )

-- Insert Alumni
INSERT  INTO @Table
        ( ID
        )
        SELECT  'A' + RIGHT('00000'
                            + CAST(MAX(RIGHT(ID, LEN(ID) - 1)) + 1 AS VARCHAR(10)),
                            5)
        FROM    @Table
        WHERE   LEFT(ID, 1) = 'A'

-- Insert Non Alumni
INSERT  INTO @Table
        ( ID
        )
        SELECT  'N' + RIGHT('00000'
                            + CAST(MAX(RIGHT(ID, LEN(ID) - 1)) + 1 AS VARCHAR(10)),
                            5)
        FROM    @Table
        WHERE   LEFT(ID, 1) = 'N'