SQL Server stored procedure generates a letter + number encoding

Source: Internet
Author: User

The equipment establish accounts function in the company's equipment management system, the function is to record the new equipment and put it into storage. One of the device number is defined as self-modification (see the previous device number, take a non-duplicate value to fill out), feel particularly troublesome! It is not more efficient to generate code automatically with stored procedures.

Requirements: According to the device Group code (PC) + increment number, constitute the encoding, the number must be three digits, no three-digit, with ' 0 ' placeholder.

The code is as follows: 

1 --Test Database Preparation2  UseMaster3 Go4 if exists(Select *  fromDbo.sysdatabaseswhereName='Hzf')5 Drop DatabaseHzf6 Go7 Create DatabaseHzf8 Go9  UseHzfTen Go One --Create a test table A ALTER proc [dbo].[get_new_id]  -     @new_id varchar( -) Output,--Number of production -     @number int,--set the maximum number of digits for an encoded number the     @group varchar(5)--numbered Letters -  as - begin -   +     Set @new_id = NULL -       +     Select Top 1 @new_id =Id fromtest_idwhereId like @group+'%' Order  by Convert(int, Right(ID,LEN(ID)-Len(@group)) )desc A       at     if @new_id  is NULL -         Set @new_id = @group+REPLICATE('0',2)+'1' -     Else -         begin -             Declare @big varchar( -) -             Set @big = Convert(int, Right(@new_id,LEN(@new_id)-Len(@group)) )+1  in             if @big < - -             begin to                 Set @big = REPLICATE('0',3-LEN(@big))+ @big +             End -             Set @new_id = @group + @big  the         End *       $  Panax Notoginseng End -   the GO +   A --Test the Declare @test int + Set @test=1 -  while(@test<= -) $ begin $     Declare @new_id    varchar( -) -     execget_new_id@new_idOutput7,'PC' -     Insert  intotest_idValues(@new_id) the     Set @test = @test+1 - EndWuyi Select *  fromtest_id

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.