1

我的表:

CREATE TABLE USER_DATA
([ID] NVARCHAR(10),[NAME] NVARCHAR(50))

我的存储过程:

CREATE PROC SP_INSERT_USER
@NAME VARCHAR(50)
AS
BEGIN
DECLARE @ID NVARCHAR(50)
DECLARE @IDTEMP INT
SELECT @IDTEMP=MAX(CAST(RIGHT([ID],3) AS INT) ) FROM USER_DATA
SELECT @IDTEMP=CASE WHEN @IDTEMP IS NULL THEN 1 ELSE  @IDTEMP+1 END 
SELECT @ID='RP'+RIGHT(('000'+CAST(@IDTEMP AS VARCHAR(10))),3)
INSERT INTO  USER_DATA VALUES (@ID,@NAME)
END

输入:

SP_INSERT_USER  'Ajit'
SP_INSERT_USER 'Amit'

输出:

ID         NAME
---------- --------------------------------------------------
RP001     Ajit
RP002     Amit

这段代码工作正常。但是ID是固定的。限制为 001、002 等 3 位数字。如果有第 1000 名员工,则无法正常显示。有没有办法让它动态而不固定长度?

4

1 回答 1

1

试试这个——

CREATE TABLE dbo.USER_DATA
(
      PK INT IDENTITY(1,1) PRIMARY KEY
    , ID AS 'PR' + RIGHT('00' + CAST(PK AS VARCHAR(5)), 5)
    , NAME NVARCHAR(50)
)

GO

CREATE PROC dbo.SP_INSERT_USER

    @NAME VARCHAR(50)

AS BEGIN

    INSERT INTO dbo.USER_DATA 
    VALUES (@NAME)

END

GO

EXEC dbo.SP_INSERT_USER 'Ajit'
EXEC dbo.SP_INSERT_USER 'Amit'

SELECT ID, NAME 
FROM dbo.USER_DATA
于 2013-06-04T09:18:16.077 回答