select 'A' + right('0000'+ltrim(isnull(cast(replace(max(c),'A','') as int),0) + 1),5) from tb
在学习中遇到这个问题 数据库里有编号字段 BH00001 BH00002 BH00003 BH00004 如何实现自动增长 --下面的代码生成长度为8的编号,编号以BH开头,其余6位为流水号。 --得到新编号的函数 CREATE FUNCTION f_NextBH() RETURNS char(8) AS BEGIN RETURN(SELECT 'BH'+RIGHT(1000001+ISNULL(RIGHT(MAX(BH),6),0),6) FROM tb WITH(XLOCK,PAGLOCK)) END GO--在表中应用函数 CREATE TABLE tb( BH char(8) PRIMARY KEY DEFAULT dbo.f_NextBH(), col int)--插入资料 BEGIN TRAN INSERT tb(col) VALUES(1) INSERT tb(col) VALUES(2) INSERT tb(col) VALUES(3) DELETE tb WHERE col=3 INSERT tb(col) VALUES(4) INSERT tb(BH,col) VALUES(dbo.f_NextBH(),14) COMMIT TRAN--显示结果 SELECT * FROM tb /*--结果 BH col ---------------- ----------- BH000001 1 BH000002 2 BH000003 4 BH000004 14 --*/ create table tb (id int identity, name varchar(10), code as 'BH'+right('0000'+cast(id as varchar),5)) go insert tb(name) select 'A' union all select 'B' union all select 'C' union all select 'D'select * from tbdrop table tb/* id name code ----------- ---------- ------------ 1 A BH00001 2 B BH00002 3 C BH00003 4 D BH00004(所影响的行数为 4 行) */
用id来吧。 'A'+right('00000'+cast(id as varchar(4)),5)
create table tb(c varchar(6)) insert tb select 'A00001' goinsert into tb select 'A' + right('0000'+ltrim(isnull(cast(replace(max(c),'A','') as int),0) + 1),5) from tbselect * from tb /* c ------ A00001 A00002(所影响的行数为 2 行)*/ insert into tb select 'A' + right('0000'+ltrim(isnull(cast(replace(max(c),'A','') as int),0) + 1),5) from tb /* c ------ A00001 A00002 A00003(所影响的行数为 3 行)*/select * from tbdrop table tb
数据库里有编号字段
BH00001
BH00002
BH00003
BH00004
如何实现自动增长 --下面的代码生成长度为8的编号,编号以BH开头,其余6位为流水号。
--得到新编号的函数
CREATE FUNCTION f_NextBH()
RETURNS char(8)
AS
BEGIN
RETURN(SELECT 'BH'+RIGHT(1000001+ISNULL(RIGHT(MAX(BH),6),0),6) FROM tb WITH(XLOCK,PAGLOCK))
END
GO--在表中应用函数
CREATE TABLE tb(
BH char(8) PRIMARY KEY DEFAULT dbo.f_NextBH(),
col int)--插入资料
BEGIN TRAN
INSERT tb(col) VALUES(1)
INSERT tb(col) VALUES(2)
INSERT tb(col) VALUES(3)
DELETE tb WHERE col=3
INSERT tb(col) VALUES(4)
INSERT tb(BH,col) VALUES(dbo.f_NextBH(),14)
COMMIT TRAN--显示结果
SELECT * FROM tb
/*--结果
BH col
---------------- -----------
BH000001 1
BH000002 2
BH000003 4
BH000004 14
--*/ create table tb
(id int identity,
name varchar(10),
code as 'BH'+right('0000'+cast(id as varchar),5))
go
insert tb(name) select 'A'
union all select 'B'
union all select 'C'
union all select 'D'select * from tbdrop table tb/*
id name code
----------- ---------- ------------
1 A BH00001
2 B BH00002
3 C BH00003
4 D BH00004(所影响的行数为 4 行)
*/
'A'+right('00000'+cast(id as varchar(4)),5)
insert tb select 'A00001'
goinsert into tb select 'A' + right('0000'+ltrim(isnull(cast(replace(max(c),'A','') as int),0) + 1),5) from tbselect * from tb
/*
c
------
A00001
A00002(所影响的行数为 2 行)*/
insert into tb select 'A' + right('0000'+ltrim(isnull(cast(replace(max(c),'A','') as int),0) + 1),5) from tb
/*
c
------
A00001
A00002
A00003(所影响的行数为 3 行)*/select * from tbdrop table tb