/*
过程名 getNum
功能: 取得指定表的下一个可用的编号
输入参数: @tablName 表名
@FileldName 即要查询的字段名.在不同的表编号所写的列名不是一样的.如有ID Num等
@Num 返回下一个可用的编号
*/
CREATE PROCEDURE dbo.getNum
@tablName VARCHAR(8),
@FileldName VARCHAR(8),
@Num VARCHAR(6) OUTPUT
AS
DECLARE @Sql VARCHAR(200)
DECLARE @oldNum INT,@newNum VARCHAR(6)
SET @Sql=''
SET @Sql='DECLARE Mycursor CURSOR FOR SELECT '+ RTRIM(@FileldName) +
' FROM ' + RTRIM(@tablName)
EXEC(@Sql)
IF @@ERROR=0
BEGIN
SET @oldNum=1
OPEN Mycursor
FETCH NEXT FROM Mycursor INTO @newNum
WHILE @@FETCH_STATUS=0
BEGIN
IF REPLICATE(0,3-LEN(@oldNum))+CAST(@oldNum AS VARCHAR) = @newNum
SET @oldNum=@oldNum+1
ELSE
BEGIN
SET @Num=REPLICATE(0,3-LEN(@oldNum))+CAST(@oldNum AS VARCHAR)
RETURN
END
FETCH NEXT FROM Mycursor INTO @newNum
END
CLOSE Mycursor
DEALLOCATE Mycursor
SET @Num=REPLICATE(0,3-LEN(@oldNum))+CAST(@oldNum AS VARCHAR)
--如果顺序没有被打断
RETURN
END
ELSE
RAISERROR
('该表或列名不存在.请检查输入的表名和列名是否正确?',7,1)
GO