0

I want to add some string with the primary key value while creating the table in sql?

Example:

my primary key column should automatically generate values like below:

'EMP101'
'EMP102'
'EMP103'

How to achieve it?

Himanshu
  • 31,810
  • 31
  • 111
  • 133
ramits
  • 39
  • 2
  • 4

7 Answers7

1

Try this: (For SQL Server 2012)

UPDATE MyTable
SET EMPID = CONCAT('EMP' , EMPID)

Or this: (For SQL Server < 2012)

UPDATE MyTable
SET EMPID = 'EMP' + EMPID
Himanshu
  • 31,810
  • 31
  • 111
  • 133
  • In the primary key column 'EMP' is constant for all the rows and i want to increment only the integers that is 101,102,103. And it should generate the primary values like 'EMP101','EMP102','EMP103'. – ramits Jul 24 '13 at 06:47
  • @ramits - How can a primary key can be 'EMP' for every row? Can you please explain what you exactly want with some sample data and expected result? – Himanshu Jul 24 '13 at 06:48
  • usually primary key column generates automatic unique numbers and my question is i want to add some string (ie) 'EMP' to that unique numbers like 'EMP101','EMP102','EMP103'. – ramits Jul 24 '13 at 06:53
  • @ramits - Then I have did the same. I have updated the answer with SQLFiddle sample. And if you want to concat EMP with PK column then your column need to be string type (e.g. `Varchar`). – Himanshu Jul 24 '13 at 06:55
  • But i want to achieve it while creating the table itself – ramits Jul 24 '13 at 06:57
  • But how can i able to auto increment the primary key column with adding some strings to it. Because it does not allow the identity property while declaring the primary key column data type as varchar. – ramits Jul 24 '13 at 07:16
  • @ramits - I have added [another answer](http://stackoverflow.com/a/17827576/1369235) for that. Please see that. – Himanshu Jul 24 '13 at 07:20
1

Since you want to set auto increment in VARCHAR type column you can try this table schema:

CREATE TABLE MyTable
    (EMP INT NOT NULL IDENTITY(1000, 1)
    ,[EMPID] AS 'EMP' + CAST(EMP AS VARCHAR(10)) PERSISTED PRIMARY KEY
    ,EMPName VARCHAR(20))
;

INSERT INTO MyTable(EMPName) VALUES
('AA')
,('BB')
,('CC')
,('DD')
,('EE')
,('FF')

Output:

|  EMP |   EMPID | EMPNAME |
----------------------------
| 1000 | EMP1000 |      AA |
| 1001 | EMP1001 |      BB |
| 1002 | EMP1002 |      CC |
| 1003 | EMP1003 |      DD |
| 1004 | EMP1004 |      EE |
| 1005 | EMP1005 |      FF |

See this SQLFiddle

Here you can see EMPID is auto incremented column with Primary key.

Source: HOW TO SET IDENTITY KEY/AUTO INCREMENT ON VARCHAR COLUMN IN SQL SERVER (Thanks to @bvr)

Community
  • 1
  • 1
Himanshu
  • 31,810
  • 31
  • 111
  • 133
0

What the rule of thumb is, is that never use meaningful information in primary keys (like Employee Number / Social Security number). Let that just be a plain autoincremented integer. However constant the data seems - it may change at one point (new legislation comes and all SSNs are recalculated).

Amit Horakeri
  • 747
  • 5
  • 18
  • 1
    The natural vs. surrogate key debate is quite old, and there are good arguments on both sides. This is too broad a statement. – jpmc26 Jul 24 '13 at 06:57
0

it seems the only reason you are want to use a non-integer keys is that the key is generated as string concatenation with another column to make it unique.

From a best practice perspective, it is strongly recommended that integer primary keys are used, but often, this guidance is ignored.

May be going through the following posts might be of help:

Should I design a table with a primary key of varchar or int?

SQL primary key: integer vs varchar

Community
  • 1
  • 1
StackTrace
  • 9,190
  • 36
  • 114
  • 202
0

You can achieve it at least in two ways:

  1. Generate new id on the fly when you insert a new record
  2. Create INSTEAD OF INSERT trigger that will do that for you

If you have a table schema like this

CREATE TABLE Table1
([emp_id] varchar(12) primary key, [name] varchar(64))

For the first scenario you can use a query

INSERT INTO Table1 (emp_id, name)
SELECT newid, 'Jhon'
  FROM
(
  SELECT 'EMP' + CONVERT(VARCHAR(9), COALESCE(REPLACE(MAX(emp_id), 'EMP', ''), 0) + 1) newid
    FROM Table1 WITH (TABLOCKX, HOLDLOCK)
) q

Here is SQLFiddle demo

For the second scenario you can a trigger like this

CREATE TRIGGER tg_table1_insert ON Table1
INSTEAD OF INSERT AS
BEGIN
  DECLARE @max INT
  SET @max = 
  (SELECT COALESCE(REPLACE(MAX(emp_id), 'EMP', ''), 0)
     FROM Table1 WITH (TABLOCKX, HOLDLOCK)
  )

  INSERT INTO Table1 (emp_id, name)
  SELECT 'EMP' +  CONVERT(VARCHAR(9), @max + ROW_NUMBER() OVER (ORDER BY (SELECT 1))), name
    FROM INSERTED
END

Here is SQLFiddle demo

peterm
  • 91,357
  • 15
  • 148
  • 157
0

I am looking to do something similar but don't see an answer to my problem here.

I want a primary Key like "JonesB_01" as this is how we want our job number represented in our production system.

--ID | First_Name | Second_Name | Phone | Etc.. -- Bob Jones 9999-999-999

--ID = "Second_Name"+"F"irst Initial+"_(01-99)"

The number 01-99 has been included to allow for multiple instances of a customer with the same surname and first initial. In our industry it's not unusual for the same customer to have work done on multiple occasions but are not repeat business on an ongoing basis. I expect this convention to last a very long time. If we ever exceed it, then I can simply add a third interger.

I want this to auto populate to keep data entry as simple as possible.

I managed to get a solution to work using Excel formulars and a few helper cells but am new to SQL.

--CellA2 = JonesB_01 (=concatenate(D2+E2))

--CellB2 = "Bob"

--CellC2 = "Jones"

--CellD2 = "JonesB" (=if(B2="","",Concatenate(C2,Left(B2)))

--CellE2 = "_01" (=concatenate("_",Text(F2,"00"))

--CellF2 = "1" (=If(D2="","",Countif($D$2:$D2,D2))

Thanks.

  • question and answere not usefull. – Neeraj Nov 09 '21 at 05:25
  • It might help the person asking the original question if he opted to use Excel to compile and append the data to his database. I was just hoping someone might have a solution entirely in SQL. To a certain extent there is an answer to the original question, but in my example the string is variable and taken from the new record itself. – RSzatkowski Nov 09 '21 at 06:43
-1
SELECT 'EMP' || TO_CHAR(NVL(MAX(TO_NUMBER(SUBSTR(A.EMP_NO, 4,3))), '000')+1) AS NEW_EMP_NO 
  FROM 
     (SELECT 'EMP101' EMP_NO 
        FROM DUAL
       UNION ALL
      SELECT 'EMP102' EMP_NO 
        FROM DUAL
       UNION ALL
      SELECT 'EMP103' EMP_NO 
        FROM DUAL 
 ) A