自动递增字母数字ID

时间:2012-12-22 06:55:26

标签: sql

希望我能在这里得到一些帮助。我有以下存储过程,它将通过插入来自@NAME的第一个字母来生成字母数字ID,即@name = Test将产生。 T001。但我试图包括前2个aplha ..即@name = Test来产生。 TE001。我尝试过更改@PREFIX VARCHAR(2)和.. SUBSTRING(@NAME, 1,2),但是当我这样做时。这些数字不会自动增加..

DECLARE @NEWID VARCHAR(5);
DECLARE @PREFIX VARCHAR(1);
SET @PREFIX = UPPER(SUBSTRING(@NAME, 1, 1))
SELECT @NEWID = (@PREFIX + replicate('0', 3 - len(CONVERT(VARCHAR,N.OID + 1))) +       CONVERT(VARCHAR,N.OID + 1)) FROM (
SELECT CASE WHEN MAX(T.TID) IS null then 0 else MAX(T.TID) end as OID FROM (
SELECT SUBSTRING(ID, 1, 1) as PRE_FIX,SUBSTRING(ID, 2, LEN(ID)) as TID FROM Testing
) AS T WHERE T.PRE_FIX = @PREFIX
) AS N

2 个答案:

答案 0 :(得分:0)

我认为这应该有效: -

DECLARE @NEWID VARCHAR(5);
DECLARE @PREFIX VARCHAR(2);
SET @PREFIX = UPPER(SUBSTRING(@NAME, 1, 2))
SELECT @NEWID = (@PREFIX + replicate('0', 3 - len(CONVERT(VARCHAR,N.OID + 1))) +       CONVERT(VARCHAR,N.OID + 1)) FROM (
SELECT CASE WHEN MAX(T.TID) IS null then 0 else MAX(T.TID) end as OID FROM (
SELECT SUBSTRING(ID, 1, 2) as PRE_FIX,SUBSTRING(ID, 2, LEN(ID)) as TID FROM Testing
) AS T WHERE T.PRE_FIX = @PREFIX
)

答案 1 :(得分:0)

试试这个

DECLARE @NEWID VARCHAR(5);
DECLARE @PREFIX VARCHAR(2);
SET @PREFIX = UPPER(SUBSTRING(@NAME, 1, 2))
SELECT @NEWID = (@PREFIX + REPLICATE('0', 3 - LEN(CONVERT(VARCHAR, N.OID + 1))) + CONVERT(VARCHAR,N.OID + 1)) 
FROM (
      SELECT CASE WHEN MAX(T.TID) IS NULL
                  THEN 0
                  ELSE MAX(T.TID) END AS OID 
      FROM (
            SELECT SUBSTRING(ID, 1, 2) AS PRE_FIX, SUBSTRING(ID, 3, LEN(ID)) AS TID 
            FROM Testing
            ) AS T 
      WHERE T.PRE_FIX = @PREFIX
      ) AS N

SQLFiddle上的演示