日期:2014-05-18  浏览次数:20592 次

有一个订货单,单据的编号是001-2006-3-31-001,001-2006-3-31-002,依此类退,这样的存储过程怎么写
有一个订货单,单据的编号是001-2006-3-31-001,001-2006-3-31-002,依此类退,我想获取我正要写入数据库的订单号,
即如果单据的编号已有001-2006-3-31-004,那么下一个编号就是今天001-2006-4-1-001
这样的存储过程怎么写
001-2006-3-31-001
001-2006-3-31-002
001-2006-3-31-003
……
001-2006-4-1-001
001-2006-4-1-002
001-2006-4-1-003
……
依此类推
我想要高效率的,这样的单据编号怎么写,订货单非常多,

------解决方案--------------------
--try

create table T(no nvarchar(20), num int)

create function dbo.get_no(
@curDate datetime
)
returns nvarchar(20)
as
begin
declare @tmp char(10)
set @tmp=convert(char(10), @curDate, 120)

declare @no nvarchar(20)
select @no=max(no) from T
where substring(no, 5, 10)=@tmp

if @no is null
set @no= '001- '+@tmp+ '-001 '
else
begin
set @no=left(@no, 15)+right( '000 '+cast(cast(right(@no, 3) as int)+1 as varchar) , 3)
end

return @no
end

insert T
select dbo.get_no(getdate()), 11
------解决方案--------------------
也寫了一個,ID可以采用默認值,插入數據的時候可以不用輸入。

不過函數中所用的方法是差不多的。

--建立函數
Create Function F_GetID(@GetDate DateTime)
Returns Char(18)
As
Begin
Declare @ID Char(18), @Date Varchar(10)
Select @Date = Convert(Varchar, @GetDate, 120)
Select @ID = Max(ID) From TEST Where CharIndex(@Date, ID) > 0
If @ID Is Null
Select @ID = '001- ' + @Date + '-001 '
Else
Select @ID = Left(@ID, 15) + Right(1001 + Right(@ID, 3), 3)
Return @ID
End
GO
--建立測試環境
Create Table TEST(ID Char(18) Default dbo.F_GetID(GetDate()), Name Varchar(10))
GO
--測試
Insert TEST(Name) Select 'A '
Union All Select 'B '
Union All Select 'C '

Select * From TEST
--刪除測試環境
Drop Table TEST
Drop Function F_GetID
--結果
/*
ID Name
001-2007-03-31-001 A
001-2007-03-31-002 B
001-2007-03-31-003 C
*/
------解决方案--------------------
create table t(bianhao varchar(100),createtime datetime)


alter procedure bianhao
as
begin
declare @re varchar(100)
declare @str varchar(100)
declare @i int
declare @str1 varchar(100)
declare @str2 varchar(100)


set @re= '001- '
set @str=convert(varchar(10),getdate(),120)
set @re=@re+@str+ '-001 '

if (select count(1) from t where bianhao=@re)=0
insert into t(bianhao,createtime) select @re,getdate()
else
begin
select @str1=bianhao from t where createtime=(select max(createtime) from t
where convert(varchar(10),createtime,120)=convert(varchar(10),getdate(),120))
set @i= cast(right(@str1,3) as int)
set @i=@i+1
set @str2= '001- '+convert(varchar(10),getdate(),120)+ '- '+
right(power(10,3),3-len(@i))+rtrim(@i)
insert into t(bianhao,createtime) select @str2,getdate()
end

end


select * from t
order by bianhao

bianhao createtime
------------------------------------------


001-2007-03-21-001 2007-03-21 14:10:34.973
001-2007-03-21-002 2007-03-21 14:10:35.533
001-2007-03-21-003 2007-03-21 14:10:35.973
001-2007-03-21-004 2007-03-21 14:10:36.373
001-2007-03-21-005 2007-03-21 14:10:36.753
001-2007-03-21-006 2007-03-21 14:10:37.047
001-2007-03-3