Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

tsql - How do I add string with auto increment value in SQL Server?

How do I add a string with auto-increment value in SQL Server?

create table date (sno int 'emp_'+ identity(1,1))

I need following as output

emp_1
emp_2
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. Define your table with a normal INT IDENTITY column
  2. Add a computed column that merges string and ID together:

Something like this:

    CREATE TABLE dbo.YourTable
       (ID INT IDENTITY(1,1),
        EmpID AS 'emp_' + CAST(ID AS VARCHAR(10)) PERSISTED, 
        ......
       )

This way, your ID column is a normal IDENTITY column, and EmpID will contain emp_1, emp_2, emp_3, ......, emp_42, ...

By making it a persisted computed column, the data is actually stored on disk and doesn't need to be re-calculated every time you access the table. Also, when persisted, you can easily put an index on that computed column, too


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...