﻿
ALTER PROCEDURE [dbo].[SpGetNewCode3]
 @tableName VARCHAR(50),/*表名*/
 @columnName VARCHAR(50),/*列名*/
 @prefix VARCHAR(100),/*流水号编码前缀*/
 @returnVal NVARCHAR(200) OUTPUT
AS
/*获取一个新的流水号（后三位上增加）*/
DECLARE 
        @sql NVARCHAR(500),
        @old NVARCHAR(50),
        @newid VARCHAR(50),
        @prefix2 NVARCHAR(100),
        @maxId NVARCHAR(50)/*已分配的最大值*/
SET @prefix2= REPLACE(@prefix, @columnName, '')
SELECT @sql=N'SELECT @maxId=MAX('+@columnName+') from '+@tableName+' where ' + @columnName + '  like ' + '''' + @prefix2 + '%'''
EXEC sp_executesql @sql, N'@maxId nvarchar(50) OUTPUT', @maxId OUTPUT 
SET @old=@maxId

IF(@old IS NULL)
BEGIN
SET @newid=@prefix+'001'
END

ELSE
BEGIN
SET @newid = (SELECT MAX(RIGHT(@old,3)))+1
SET @newid = @prefix +RIGHT('000'+@newid,3)
END

SET @returnVal=@newid

GO 

