--下面的代碼生成長度為12的編號,編號以BH開頭,前四位數字為col字段,其余6位為流水號。 --得到新編號的函數 alter FUNCTION f(@col int) RETURNS char(12) AS BEGIN RETURN(SELECT 'BH'+RIGHT(10000+@col,4)+RIGHT(1000001+ISNULL(RIGHT(MAX(BH),6),0),6) FROM tb WITH(XLOCK,PAGLOCK) where col=@col) END GO --在表中應用函數 drop table tb; CREATE TABLE tb( BH char(12) PRIMARY KEY, col int not null) --插入資料 BEGIN TRAN INSERT tb(BH,col) VALUES(dbo.f(1),1) INSERT tb(BH,col) VALUES(dbo.f(2),2) INSERT tb(BH,col) VALUES(dbo.f(3),3) INSERT tb(BH,col) VALUES(dbo.f(4),4) INSERT tb(BH,col) VALUES(dbo.f(1),1) INSERT tb(BH,col) VALUES(dbo.f(1),1) INSERT tb(BH,col) VALUES(dbo.f(1),1) INSERT tb(BH,col) VALUES(dbo.f(2),2) INSERT tb(BH,col) VALUES(dbo.f(2),2) INSERT tb(BH,col) VALUES((SELECT 'BH'+RIGHT(10000+2,4)+RIGHT(1000001+ISNULL(RIGHT(MAX(BH),6),0),6) FROM tb WITH(XLOCK,PAGLOCK) where col=2) ,2) COMMIT TRAN --顯示結果 SELECT * FROM tb /*結果 BH0001000001 1 BH0001000002 1 BH0001000003 1 BH0001000004 1 BH0002000001 2 BH0002000002 2 BH0002000003 2 BH0002000004 2 BH0003000001 3 BH0004000001 4 */