0

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
4
  • autoincrement string? huh? a, b, c, ...? Commented Nov 17, 2011 at 16:46
  • Sounds like something a trigger would be useful for. Commented Nov 17, 2011 at 16:47
  • Can you clarify your question? Commented Nov 17, 2011 at 16:48
  • It looks like the goal is for the the sno column to hold values as follows: emp_1, emp_2, emp_3, etc... Is this correct? Commented Nov 17, 2011 at 16:53

3 Answers 3

11
  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

Sign up to request clarification or add additional context in comments.

Comments

1

You can't use any string as autoincrement

Lets think you have a table

|- id -|- name -|
|-  1 -|- Utku -|
|-  2 -|- Gopi -|

Lets select them as emp_1,emp_2

SELECT CONCAT("emp_",id) AS emp_id,name
FROM table

Result:

|- emp_id -|- name -|
|-  emp_1 -|- Utku -|
|-  emp_2 -|- Gopi -|

1 Comment

concantenating in every query is a bad idea. Please look at @marc_s's solution.
0

Try using computed column MSDN

CREATE TABLE Yourtablename
(
    ID int IDENTITY (1,1) NOT NULL
    InvoiceID AS 'INV'+ right('000000' cast(ID as varchar(20),7)
);

1 Comment

Are you sure this answer is for this or stackoverflow.com/questions/31468567/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.