[MSSQL]開發之 使用觸發器自動編號

來源:互聯網
上載者:User

 SQL Server 開發之 使用觸發器自動編號 收藏
使用SQL Server建立數字類型的欄位,可以設定為自動編號。但很多時候並不能滿足我們的需求,例如為學生編號時,可能要用到年級、系別等再加上流水號進行編號。下面給一個簡單的例子,使用觸發器來進行自動編號。

  --建立測試表  

  if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usertable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  drop table [dbo].[usertable]
GO

  create   table  usertable(userid   varchar(20),username   nvarchar(20))  
   go  

  --建立觸發器  
  create   trigger  tg_insert  on   usertable  
    for   insert   
  as   
    declare   @username nvarchar(20)  
    declare   @userid   varchar(20)  
    declare   @num      int  
    declare   @strNum   varchar(20)
    declare   @prefix   varchar(10)
    declare   @Numlen   int
    declare   @strDate  varchar(20)
    --擷取當前日期
    set @strDate=substring(convert(varchar(10),getdate(),112),1,8)
    --設定流水號的長度
    set @Numlen = 4
    --設定首碼
    set @prefix = 'S'
    select   @userid=max(userid)  from  usertable  
      where   userid   like   @prefix   +  @strDate   +   '%'  
    if @userid is null   
        set @num=0 
    else
        set @num=cast(replace(@userid,@prefix + @strDate ,'') as int)  
    set  @num = @num + 1
    set  @strNum = cast(@num as varchar(10))
    while(len(@strNum)<@Numlen)
         set @strNum = '0' + @strNum
    set   @userid=@prefix +  @strDate + @strNum
    select   @username=username   from   inserted  
    rollback   
    insert   into   usertable   values(@userid,@username)      

  go       

  --測試  

  insert   into   usertable(username)   values('aa')  
  go  
  insert   into   usertable(username)   values('bb')  
  go  
  insert   into   usertable(username)   values('cc')  
  go  

  --顯示資料  
  select   *   from   usertable  
  go

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/fengfangfang/archive/2006/06/29/850431.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.