利用SQL預存程序產生程式編號的一種方法

來源:互聯網
上載者:User
在程式設計中,尤其是針對公司專屬應用程式的開發,不可以避免的會要產生大量的編號,比如訂單編號、入庫編號等。現在利用SQL的預存程序可以方便的實現自動編號,可以大大的提高程式的複用和減少代碼的編寫。

        主要是利用SQL中的CONVERT函數來對日期進行格式化。
        比如要做這樣的一個編號結構:
        標識(2位)           日期時間(14位)            流水號(4位)
        BH                             20070227160954               1001

        程式碼如下:   

       

DECLARE @myval nvarchar(20),
 @maxval nvarchar(4)

select @maxval=max(right(InEquipNum,4))+1 from InEquip  --InEquipNum 為編號欄位,取最後4位並加1

set @myval=CONVERT(varchar(12), getdate(),112)+           --取日期組合
(substring(convert(varchar(20),getdate(),120),12,2)) +        --取小時
(substring(convert(varchar(20),getdate(),120),15,2)) +        --取分鐘
(substring(convert(varchar(12),getdate(),108),7,2)) +          --取秒
(select case  
    when @maxval is null then '1000'                                           --如果編號為空白,則先給出一個值
    else @maxval
    end
)

select @myval 編號

       運行後結果如:BH200702271609541001

       附CONVERT函數使用說明:
       使用 CONVERT:
CONVERT (data_type[(length)], expression [, style])

select CONVERT(varchar, getdate(), 120 )
2004-09-12 11:06:08
select replace(replace(replace(CONVERT(varchar, getdate(), 120 ),\'-\',\'\'),\' \',\'\'),\':\',\'\')
20040912110608
select CONVERT(varchar(12) , getdate(), 111 )
2004/09/12
select CONVERT(varchar(12) , getdate(), 112 )
20040912
select CONVERT(varchar(12) , getdate(), 102 )
2004.09.12
select CONVERT(varchar(12) , getdate(), 101 )
09/12/2004
select CONVERT(varchar(12) , getdate(), 108 )
11:06:08

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.