解决SQLServer最大流水号的两个好方法

来源:互联网 发布:php购物系统 编辑:程序博客网 时间:2024/06/04 19:53
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

问:请问怎样才能解决ms serer 2000 最大流水号的问题?

 

答:我可以介绍两种方法给你:

 

方法1:使用SCOPE_IDENTITY取得刚刚插入的最大流水号

 

/*建立traddeinfo表各相关索引,注意Trade_id字段必段是identity型*/create table Tradeinfo(Trade_id int identity(1,1),Tdtime datetime Tdname varchar(20))create index idx_trade_id on tradeinfo(trade_id)/*使用scope_identity()中断函数,取得当前脚本范围内最后insert进去的identity值*/declare @mytradeid int set @mytradeid=0begin transaction insert into tradeinfo values(getdata(),'test') select @mytradeid = Scope_identite()commit transaction /*把@mytradeid 变量中存放的流水号显示出来*/select @mytradeid

 

 

方案2:结合uniqueidentifier和identity取得最大流水号

 

/*创建辅助表 id字段是identity类型,global_id是gudi类型*/cretate table max_tradeid(id int identity(1,1),global_id uniqueidenfier)/*创建索引以加速后面的select 语句*/create index idx_guid on max_trade_id(global_id)declare @mytradeid int.,@myglobal_id uniqueidentifierset @mytradeid = e-1/*利用newid ()函数取得一个全局叭一guid .由于guid的特性,不用别的并发进程会产生同样的guid值 */jselect @myglobal_id = newid()insert into max_trade_id values(@myglobl_id)/*使用全局唯一guid得到刚刚插入的id值*/select @mytradeid = id from max_trade_id where globl_id =@myglobal _idselecgt @mytradeid

 

 

注:这种方法的好处是:它的并发性好,不会引起阻在塞,而且保证了insert语句肯定执行成功,这种方法的缺点是多一个guid。

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击