SQL Server writes automatically-increasing string-type primary keys. SQL Server

Source: Internet
Author: User
Tags key string

SQL Server writes automatically-increasing string-type primary keys. SQL Server

1. Compile the scalar value function ICONVERT2STRING

CREATE FUNCTION ICONVERT2STRING(@N INT,@F INT) RETURNS VARCHAR(10) ASBEGINDECLARE @M INTDECLARE @L0 INTDECLARE @CH VARCHAR(10)DECLARE @ST VARCHAR(20)SELECT @CH=''SELECT @ST=CONVERT(VARCHAR(10),@N)SELECT @ST=RTRIM(@ST)SELECT @L0=LEN(@ST)SELECT @M=1WHILE (@M<=@F-@L0)BEGINSELECT @CH=@CH+'0'SELECT @M=@M+1ENDSELECT @ST=@CH+@STRETURN @STEND
Note: @ F is the length of the variable part after the string.

2. Compile the scalar value function GetUnitSNo that returns the primary key string.

CREATE function GetUnitSNo() returns char(8) as beginDeclare @mystr char(8)Declare @str0 char(2)Declare @count intDeclare @MaxEnd intDeclare @st1 char(10)select @str0='US'select @count=count(*) from Unit_Sif @count=0select @MaxEnd=0elseselect @MaxEnd=max(substring(U#,3,len(U#)-1)*1) from Unit_S SELECT @st1=DBO.ICONVERT2STRING(@MaxEnd+1,6)select @mystr=@str0+ LTRIM(RTRIM(@st1))return @mystrend
Note: The Stored Procedure of the returned primary key string has not been implemented ....
3. effect display

SQL query statement: SELECT DBO. GetUnitSNo ()

Query Result: US000001 (the records in the Unit_S table are empty)

4. C # frontend call

String USNO = DB. ExecuteSQLScalarTOstring ("select dbo. GETUNITSNO ()");


Auto-numbered SQL server 2005 Enterprise Manager

Auto-increment cannot start with 0001. The auto-increment type can only be numerical, so it should start from 1.
Custom addition:




How to auto-increment primary keys of the primary SQL SERVER

Auto-increment columns are only applicable to numeric fields. If character fields are used, you must manually trigger them to implement auto-increment.

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.