34,591
社区成员
发帖
与我相关
我的任务
分享
CREATE VIEW v_GetDatedeclare @id int
set @id=5
select 'D'+convert(varchar(4),getdate(),120)+right('00000'+convert(varchar,@id),5) as dh
/*
dh
-----
D200900005
(1 行受影响)
*/
select 'D'+convert(varchar(4),getdate(),120) as dh
/*
dh
-----
D2009
(1 行受影响)
*/
create table #test
(id int identity,
FormatId as 'SL'+right(10000000+id,6),
F1 varchar(50))
go
insert #test(F1) select '1'
union all select '2'
select * from #test
drop table #test
/*
id FormatId F1
----------- -------------- -----
1 SL000001 1
2 SL000002 2
(所影响的行数为 2 行)
*/
create proc pr_test
as
begin
select 'D'+ltrim(datepart(yy,getdate()))+'0001'
end
go
exec pr_test
/*
-----------------
D20090001
(1 行受影响)
*/
drop proc pr_test
--以下代码生成的编号长度为12,前6位为日期信息,格式为YYMMDD,后6位为流水号。
--创建得到当前日期的视图
CREATE VIEW v_GetDate
AS
SELECT dt=CONVERT(CHAR(6),GETDATE(),12)
GO
--得到新编号的函数
CREATE FUNCTION f_NextBH()
RETURNS char(12)
AS
BEGIN
DECLARE @dt CHAR(6)
SELECT @dt=dt FROM v_GetDate
RETURN(
SELECT @dt+RIGHT(1000001+ISNULL(RIGHT(MAX(BH),6),0),6)
FROM tb WITH(XLOCK,PAGLOCK)
WHERE BH like @dt+'%')
END
GO
--在表中应用函数
CREATE TABLE tb(
BH char(12) PRIMARY KEY DEFAULT dbo.f_NextBH(),
col int)
--插入资料
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)
--显示结果
SELECT * FROM tb
/*--结果
BH col
------------------- -----------
050405000001 1
050405000002 2
050405000003 4
050405000004 14
--*/