SQL Server writes a string-type primary key that grows automatically

Source: Internet
Author: User
Tags key string rtrim scalar

1. Write scalar value function iconvert2string

CREATE FUNCTION iconvert2string (@N int,@f INT) RETURNS varchar (ten) Asbegindeclare @M intdeclare @L0 intdeclare @CH VARCHAR (10) DECLARE @ST VARCHAR () Select @CH = "Select @ST =convert (VARCHAR), @N) Select @ST =rtrim (@ST) Select @L0 =len (@ST) Select @m=1while (@m<[email protected] @L0) beginselect @[email protected]+ ' 0 ' SELECT @[email protected]+1endselect @[email Protected][email Protected]return @STEND
Description: The parameter @f is the length of the variable part after the string.

2. Write a scalar-valued function that returns a primary key string Getunitsno

CREATE function Getunitsno () returns char (8) as Begindeclare @mystr char (8) Declare @str0 char (2) Declare @count intDECLARE @MaxEnd intDECLARE @st1 char (TEN) Select @str0 = ' US ' select @count =count (*) from unit_sif @count =0select @MaxEnd = 0elseselect @MaxEnd =max (substring (U#,3,len (u#)-1) from unit_s SELECT @st1 =dbo. Iconvert2string (@MaxEnd +1,6) Select @[email protected]+ LTRIM (RTRIM (@st1)) return @mystrend
Description: A stored procedure that returns a primary key string has not been implemented ....
3. Effect Display

SQL query statement: SELECT DBO. Getunitsno ()

Query Result: US000001 (case where the record in the unit_s table is empty)

4. C # frontend Call

String USNO = DB. Executesqlscalartostring ("Select DBO. Getunitsno () ");

SQL Server writes a string-type primary key that grows automatically

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.