如何根据条件插入记录时生成自定义ID?例如,我有一个donor database program
,可以接受来自non-alumni
和alumni
的捐款。校友的自定义ID应从A00001
开始,非校友的自定义ID为N00001
。值得注意的是,将要插入的记录将来自另一个记录来自excel文件的表。
任何帮助或澄清将不胜感激。
答案 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'