3

希望我能在这里得到一些帮助。我有以下存储过程,它将通过插入@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
4

2 回答 2

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
)
于 2012-12-22T07:04:08.980 回答
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上的演示

于 2012-12-24T13:21:52.750 回答