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

自动编号的问题
现在想用c#写一个自动增加编号的函数,最终得出一个单号,如:J2007082001   .(结构为字母+年+月+日+自动生成的编号).最后自动生成的编号是当天增加的单号的序号.比如当天增加了三笔单号,那么单号为:J2007082001   ,J2007082002   ,J2007082003.第二天的单号为第二天的日期加自动生成的编号:   J20070821001,J20070821002.
    请教各位高手是怎么实现的.谢谢!


------解决方案--------------------
c#写怎么发到sql版来了

幸好我这里有个例子,改了一下,

假设你有个 [表] 里面有个字段存放单号,代码如下:

string strNO = " "; //单号
string strSql = "select [单号] from [表] where [单号] like 'J " + DateTime.Now.ToString( "yyyyMMdd ") + "% ' ";
SqlConnection cnn = new SqlConnection( "连接字符串 ");
SqlCommand cmd = new SqlCommand(strSql,cnn);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read()) //如果有就加1
{
strNO = dr[0].ToString();
strNO = strNO.Substring(0,9) + Convert.ToString(int.Parse(strNO.Substring(10,1)) + 1).PadLeft(2, '0 ');
}
else //没有就是01了
{
strNO = "J " + DateTime.Now.ToString( "yyyyMMdd ") + "01 ";
}
dr.Close();

Response.Write(strNO);
------解决方案--------------------
create table tb(ID nvarchar(20),col nvarchar(10))
go

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


Create function f_getID()
returns nchar(11)
as
begin
declare @ID int
declare @Nowdate nvarchar(8),@OtherDate nvarchar(8),@Num nchar(13)
select @Nowdate = convert(char(8),getdate(),112),@OtherDate = '19990101 ',@ID = 0,@Num = ' '
select @OtherDate = substring(ID,2,8),@ID = right(ID,2) from tb where substring(ID,2,8) = @Nowdate
if @OtherDate <> @Nowdate
begin
select @ID = 0
end;
select @Num = 'J ' + @Nowdate + right((100 + @ID + 1),2)
return @Num
end

insert into tb
select dbo.f_getID(), 'aa '

select * from tb