SQL Server identity counterpart problem - sql-server-2005

I'm using SQL Server and I want to use identity constraint in it
I know how to use it in following manner
create table mytable
(
c1 int primary key identity(1,1);
)
the above code works fine but what if i want the identity column to have values as EMP001, EMP002,... instead of 1,2....
Thanks in advance,
Guru

Identity columns can only be integers. If you want it to "look like" EMP001, EMP002, etc then that's simply a display issue and not a storage one (that is, you don't need to store "EMP001", "EMP002" etc, just store it as 1, 2, 3 via a normal identity column and display it in your application as "EMP001", "EMP002", etc)

Create a computed column that concatenates like this:
'EMP' + RIGHT('00' + CAST(c1 AS varchar(3)), 3)
Otherwise an IDENTITY column as surrogate key is just that: a meaningless number.
I assume you're only going to have 999 rows or is there another sequence somewhere?

Related

How to make an auto-incrementing id column use missing numbers in SQL Server?

Say I have a table with 100 rows and an auto-incrementing id column, and I delete the row with id = 15. How can I add a new row with id = 15 instead of id = 101?
No, don't do it.
Generated primary keys are used to produce unique values, that are of internal use. They are not supposed to "sexy" or nice looking. That is NOT their purpose; the PK purpose is uniqueness. If you are concerned about the specific values, then it means you are exposing the PK to the external world... something that raises a lot of red flags.
If you need a value to expose, don't use the PK fot this, but create a secondary column for it. Its solely purpose in the world is to be exposed. This value can have a nice formatting with dashes (like the SSN), prefixes, suffixes, etc.
If you have a table with an identity key field you could use this:
SET IDENTITY_INSERT YourTableName ON
INSERT INTO YourTableName (ID, Other) VALUES (15, 'Whatever')
SET IDENTITY_INSERT YourTableName OFF

SQL Server - Reset custom identity column

I have a table with two columns ID and SubDetail. I have created custom identity like 2018XX for the ID columns with 2018 as current year and XX as a number and it will start from "01". I have searched for some topic about "Reset identity field - SQL Server" but It only showed how to reset only number identity field. I'm confused that is there anyway to reset custom identity field.
Here is my SQL query code:
CREATE PROCEDURE spAddSubWareHouse
(#SubDetail VARCHAR(50))
AS
BEGIN
DECLARE #maxDetailID INT
SELECT #maxDetailID = MAX(CAST(RIGHT(ID, 2) AS INT))
FROM SubWareHouse
IF (#maxDetailID IS NULL)
SET #maxDetailID = 1
ELSE
SET #maxDetailID += 1
--insert
INSERT INTO SubWareHouse
VALUES (CAST(YEAR(GETDATE()) AS VARCHAR) + RIGHT('00' + CAST(#maxDetailID AS VARCHAR), 2), #SubDetail)
END
Don't bother doing this. Simply have a numeric identity column defined as:
id int identity(1, 1) primary key
You can then store the year as a separate column, because that appears to be information that you want.
Why do it this way? There are many reasons. First, identity is built into the database. So, identity columns are guaranteed to be unique even when multiple applications are doing inserts at the same time.
Second, integers are more efficient (slightly) for foreign key references.
Third, the locking required to do what you really want is very cumbersome and could significantly slow down your system. Plus, any implementation to prevent duplicates could have a bug -- so why not use the built-in mechanisms?
If you need to get the sequence number for a given year, it is easy enough using row_number():
select row_number() over (partition by year order by id) as year_sequence_number

SQL simplist way to update an INT identity column

I have a column called fixedID, and it's current Value = 2, I want to update this value to be 42. What is the best way to do this. I would like to do this modification as simply as possible. However, if I could do this while doing an select insert that would be fantastic also.
update tblFixedId
set FixedId = (FixedId + 400)
possible to change the value here?
Select * INTO mynewTable from myOldertable
Identity columns are not updatable in SQL Server.
The only way of doing this as an actual UPDATE rather than a DELETE ... INSERT would be to use ALTER TABLE ... SWITCH to mark the column as no longer an IDENTITY column, do the UPDATE then ALTER TABLE ... SWITCH again to re-mark the column as IDENTITY (For example code the first way round see the workarounds on this Connect Item and for the second way here).
Note that in the common scenario that the identity column is the clustered index key the Update will likely be implemented as an INSERT ... DELETE anyway.

SQL Identity with leading padded zeros

I have marked a column as Identity in my table
create table Identitytest(
number int identity(1,001) not null,
value varchar(500)
)
I need the identity column to be incremented as 001,002,003, etc.
The database shows that it is inserting as 1,2,3, etc.
How can this be done?
As the others have already rightfully pointed out - an INT never has leading zeroes - it just holds the value, that's all (and that's good that way).
If you need some additional formatting, you could always add a computed column to your table, something like:
ALTER TABLE dbo.Identitytest
ADD DisplayNumber AS RIGHT('000' + CAST(number AS VARCHAR(3)) , 3) PERSISTED
This way, your INT IDENTITY will be used as an INT and always contains the numerical value, while DisplayNumber contains 001, 002, ... 014, 015, ..... and so forth - automagically, always up to date.
Since it's a persisted field, it's now part of your table, and you can query on it, and even put an index on it to make queries faster:
SELECT value FROM dbo.IdentityTest WHERE DisplayNumber = '024'
And of course, you could use just about any formatting in the definition of your computed column, so you could also add a prefix or something:
ALTER TABLE dbo.Identitytest
ADD DisplayNumber
AS 'ABC-' + RIGHT('000' + CAST(number AS VARCHAR(3)) , 3) PERSISTED
So in this case, your DisplayNumber would be ABC-001, ABC-002, ... and so on.
You get the best of both worlds - you keep your INT IDENTITY which is numerical and automatically increased by SQL Server, and you can define a display format any way you like and have that available at any time.
If you want to display your number column with leading zeros, just pad it in your SELECT statement. It's a number, it will NOT store with leading zeros as an integer.
SELECT RIGHT('00000' + CAST([number] AS varchar(5)) , 3)
FROM IdentityTest
The 3 is the number of characters you want total in the output display.
If you require both the auto-incrementing number (which can only be a number) and an alphabetic representation of the number, you might consider looking at computed columns.
Here's a few links to get you going:
http://www.mssqltips.com/tip.asp?tip=1682
http://msdn.microsoft.com/en-us/library/ms191250.aspx
http://www.kodyaz.com/articles/sql-server-computed-column-calculated-column-sample.aspx
Why do you need that? As an integer, 001 is the same as 1. If what you want is that for display or other purposes, create another column and do your work there (you may do it as part of a trigger on the table, on insert, that looks at the newly inserted row, and creates the entry in the column appropriately.
i've got a table where i'm storing an integer, but the users want to see it a XXX, even if it has zeroes, so i wrote this code
declare #a int
set #a=1
select replicate('0',3-len(#a))+ cast(#a as varchar(4))
Here is another method:
create table TEST_T (ui int NOT NULL identity, name varchar(10))
insert into TEST_T values ( 'FRED' )
select NAME, ui, RIGHT('0000' + LTRIM(STR(ui)), 4) as ui_T from TEST_T
go
/* NOTE: A view could be created with a calculated column instead of the identity column. */
create view TEST_V as select NAME, RIGHT('0000' + LTRIM(STR(ui)), 4) as ui_V from TEST_T go
go
select * from TEST_V
drop view TEST_V
drop table TEST_T
Not quite as much data duplication(?) as adding a column to the table and no need to specify the column in the select statement.
I need the identity column to be
incremented as 001,002,003, etc.
The database shows that it is
inserting as 1,2,3, etc.
SQL databases store values, not the literals you used to write those values. 002 is 2. Just like 1 + 1 is 2. Would you expect SELECT 1 + 1 to display the string "1 + 1" instead of 2?
If you want the leading zeros to be stored in your column, you have to use a character type. But then you can't use AUTOINCREMENT/IDENTITY.
What you probably really want is something like printf("%03d", number) in program that reads from the database.

Generating Random ID's in Microsoft SQL Server

I want to create a table in sql server and fill it up with data (people's info) every person should have a unique ID different than the auto incremented ID's by sql server
For example i need the ID for the first person inserted like this: 2016xxxx
how to fix the 2016 and randomly generate the numbers after that to be filled instead of xxxx
should i use a regular expression ?
You can also create a computed column like below
CREATE TABLE tableName
(
PkAutoId INT PRIMARY KEY IDENTITY(1,1),
PersonUniqueNo AS (CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR) + RIGHT(RIGHT(CAST(RAND() AS VARCHAR),4) + CAST(PkAutoId AS VARCHAR),4))
)
Computed Column "PersonUniqueNo" is 8 Digit Unique Number comprising of Current Year And Conceited value of Random number and Primary Key Id for 4 Length, Total length will be 8 as asked.
You could create a function that would get the next value for you and use that instead of an AUTO_INCREMENT field.
I wouldn't recommend it tho. You shouldn't format the data like that before inserting it. That sort of thing should be done on the way out, preferably by the front-end code. Or you can just write a query and create a view ...
However if you must do that here is the complete answer with the code:
Is there a way to insert an auto-incremental primary id with a prefix in mysql database?