SQL Server: Auto increment char pk - sql-server

Is it possible to have a char primary key on a table? For example 'WC001' then will it automatically increment by 1, so the next record for the pk will be 'WC002' and so on.
Can anyone provide me example?
Thanks

Not directly - but you could have a normal INT IDENTITY auto-incrementing numerical ID and then defines a computed persisted column (SQL Server 2005 and newer) - something like:
CREATE TABLE dbo.YourTable
(ID INT IDENTITY(1,1),
CharID AS 'WC' + RIGHT('000' + CAST(ID AS VARCHAR(3)), 3) PERSISTED,
CONSTRAINT PK_YourTable PRIMARY KEY(CharID)
)
Inserting values into this table will cause the ID column to be 1, 2, 3, 4, 5, ..... and the CharID column will automatically be WC001, WC002, WC003 and so forth.
Since it's a persisted computed column, the values is always up to date, and you can even put an index (like the primary key) on it.

Not easily, but if you need something like this there's nothing stopping you from breaking up the alpha and numeric portions of your key. Make the WC portion AKey and the numeric be NKey, and auto-inc the Nkey.
If you want you can expose it in a view as:
SELECT AKey + CAST(nkey as varchar) as 'Key'
...
Implementing a "custom" identity never works out well since there are so many factors involved with resolving concurrency issues efficiently.
SQL Server 2012 will add support for more complicated identity fields.

My suggestion is to create another column named Id IDENTITY(1,1) INT and then make your desired column as computed column which will consist of Id and formatted number of 0s.

Related

SQL Server : identity and autoincrement for varchar

This is my first question on this platform. I am working on a database project. I want to use autoincrement for my primary key for id, but also want to add an alphabet before it. Are there other ways to do it apart from using 2 columns declaring one as identity and casting the other? I have worked with stored procedures and triggers.
Thank you
PS: I want to do it using one column if possible
You won't be able to do this with just one column.
The best solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.tblCompany
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
CompanyID AS 'CMP-' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblCompany without specifying values for ID or CompanyID:
INSERT INTO dbo.tblCompany(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will increase your ID value, and CompanyID will contain values like CMP-00001, CMP-00002,...... and so on - automatically. The CompanyID column will be fill automatically, by SQL Server, upon inserting a new row - so there's no need for triggers or stored procedures or anything else - just this declaration in your table definition.
UPDATE: if you're using SQL Server 2012 or newer, you can do it with just one column - if you also create a SEQUENCE - like this:
CREATE SEQUENCE SEQ_CompanyID
AS INT
START WITH 1000
INCREMENT BY 1;
CREATE TABLE dbo.Company
(
CompanyID VARCHAR(20) NOT NULL
CONSTRAINT DF_CompanyID
DEFAULT('CMP-' + CAST(NEXT VALUE FOR dbo.SEQ_CompanyID AS VARCHAR(10))),
CompanyName VARCHAR(100) NOT NULL,
----- other columns here
)
Now if you make sure to insert with omitting the CompanyID column in the insert statement, like this:
INSERT INTO dbo.Company (CompanyName)
VALUES ('Company #1'), ('Company ABC'), ('Company Three');
then you get CMP-1001', 'CMP-1002 etc. as your CompanyID, again, automatically handled by SQL Server upon inserting a new row.

How to auto increment in vb form

I am using vb.net and SQL Server as backend; I want to auto generate id which is created as primary key and is there any way to auto generate id with alphanumeric ex:- cx10001,cx1002
The best solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.YourTable
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
YourOtherId AS 'cx' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into YourTable without specifying values for ID or YourOtherID:
INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and YourOtherID will contain values like cx00001, cx00002,...... and so on - automatically, safely, reliably, no duplicates.

reverting alpha numeric identity

I see this question has been asked numerous times with rather good results, however this one differs in that we want to revert to a normal auto increment ID after we have added alpha numberic IDs.
We have 3 databases that will eventually all combine into a single database. In order for our system to remain compliant we need the IDs to persist over the merge. So far we have managed to combine the data in an alphanumeric fashion where we prefix the record ID with the database source, such as IDs that came from DBAA is now AA## and DBBB is now BB##.
The question now though, is it possible to revert the varchar ID column back to an auto increment integer without adding more columns or creating functions in the back end? The idea is that the next entry in the new merged DB will be one higher than the highest of the 3 DBs, so if AA10 was highest then the next entry would be 11. (with no prefix and no function in the back end)
CREATE TABLE tableTest
(
colID varchar(50) PRIMARY KEY,
[desc] varchar(10) NOT NULL
)
ALTER TABLE tableTest ALTER COLUMN colID int NOT NULL IDENTITY(1,1)
of course as you can imagine that didn't work. Ultimately I just want to know if this is even possible to do without back end functions or additional columns.
So, to sum up Sean's and my comments - the answer is no.
This is impossible for many reasons.
You can manipulate the data in that column to create unique numeric values (that is providing your values are unique as is right now) - something like this will do the trick:
UPDATE tableTest
SET colId = REPLACE(REPLACE(REPLACE(colId, 'AA', ''), 'BB', ''), 'CC', '') +
CASE
WHEN colId LIKE 'AA%' THEN '1'
WHEN colId LIKE 'BB%' THEN '2'
WHEN colId LIKE 'CC%' THEN '3'
END
This way your current number part stays the most significant digits - so if your table contained values like
. AA1, BB5, CC7, AA30, BB12, it will now contain these values:
. 11, 52, 73, 301, 122 - as you can see, the "order" is preserved.
Another option is to add a new identity column, delete the current colID column, and rename the identity column to colID.
This can be achieved either by using ssms's table designer or by using sp_rename.
Note that if you are not using the table designer you will have to first drop the primary key constraint before you can drop the column.

How to allow in the field with a unique constraint to enter a lot of null values in SQL Server

create table test3
(
id int PRIMARY KEY,
id2 int
);
create unique index ndx_id2 on test3 (id2);
For the purposes of unique indices, all NULL values are considered to different from all other NULL values and are thus unique. This is one of the two possible interpretations of the SQL-92 standard (the language in the standard is ambiguous) and is the interpretation followed by PostgreSQL, MySQL, Firebird, and Oracle.
Informix and Microsoft SQL Server follow the other interpretation of the standard.
INSERT INTO test3(id, id2) VALUES (1, null);
INSERT INTO test3(id, id2) VALUES (2, null);
Second INSERT returns
A duplicate value cannot be inserted into a unique index. [ Table name
= test3,Constraint name = ndx_id2 ]
Error in SQL Server but successfully adds record to another DBMS, Sqlite for example.
How to allow in the field with a unique constraint to enter a lot of null values ​​in SQL Server?
From SQL Server 2008 and onwards, you can use a filtered index:
create unique index UX_YourIndex
on YourTable(col1)
where col1 is not null
Example at SQL Fiddle.
For SQL Server 2005 and older (9.0 corresponds to 2005), you can use a surrogate column. A surrogate column is a computed column. It is computed as follows:
When the semi-unique column is not null, the surrogate column is equal to that column
When the semi-unique column is null, the surrogate column is equal to a unique id. A unique id can be an identity column, a rowguid, or anything that is different for each row.
In other words, the surrogate column uses a unique string whenever the original column is null. For example:
create table YourTable
(
id int identity primary key
, col1 int
, surrogate1 as (coalesce(convert(varchar(20), col1), '_' + convert(varchar(20), id)))
);
create unique index UX_YourIndex on YourTable(surrogate1);
It's your job to make sure that the surrogate values do not collide with real values. In this example, I'm assuming that col1 cannot start with an underscore.
Example at SQL Fiddle.

Auto increment primary key in SQL Server Management Studio 2012

How do I auto increment the primary key in a SQL Server database table? I've had a look through the forum but can't see how to do this.
I've looked at the properties but can't see an option. I saw an answer where you go to the Identity specification property and set it to yes and set the Identity increment to 1, but that section is grayed out and I can't change the no to yes.
There must be a simple way to do this but I can't find it.
Make sure that the Key column's datatype is int and then setting identity manually, as image shows
Or just run this code
-- ID is the name of the [to be] identity column
ALTER TABLE [yourTable] DROP COLUMN ID
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)
the code will run, if ID is not the only column in the table
image reference fifo's
When you're creating the table, you can create an IDENTITY column as follows:
CREATE TABLE (
ID_column INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
...
);
The IDENTITY property will auto-increment the column up from number 1. (Note that the data type of the column has to be an integer.) If you want to add this to an existing column, use an ALTER TABLE command.
Edit:
Tested a bit, and I can't find a way to change the Identity properties via the Column Properties window for various tables. I guess if you want to make a column an identity column, you HAVE to use an ALTER TABLE command.
You have to expand the Identity section to expose increment and seed.
Edit: I assumed that you'd have an integer datatype, not char(10). Which is reasonable I'd say and valid when I posted this answer
Expand your database, expand your table right click on your table and select design from dropdown.
Now go Column properties below of it scroll down and find Identity Specification, expand it and you will find Is Identity make it Yes. Now choose Identity Increment right below of it give the value you want to increment in it.
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):
Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?
Example:
CREATE SCHEMA blah.
GO
CREATE SEQUENCE blah.blahsequence
START WITH 1
INCREMENT BY 1
NO CYCLE;
CREATE TABLE blah.de_blah_blah
(numbers bigint PRIMARY KEY NOT NULL
......etc
When referencing the squence in say an INSERT command just use:
NEXT VALUE FOR blah.blahsequence
More information and options for SEQUENCE
When you're using Data Type: int you can select the row which you want to get autoincremented and go to the column properties tag. There you can set the identity to 'yes'. The starting value for autoincrement can also be edited there. Hope I could help ;)
I had this issue where I had already created the table and could not change it without dropping the table so what I did was:
(Not sure when they implemented this but had it in SQL 2016)
Right click on the table in the Object Explorer:
Script Table as > DROP And CREATE To > New Query Editor Window
Then do the edit to the script said by Josien; scroll to the bottom where the CREATE TABLE is, find your Primary Key and append IDENTITY(1,1) to the end before the comma. Run script.
The DROP and CREATE script was also helpful for me because of this issue. (Which the generated script handles.)
You can use the keyword IDENTITY as the data type to the column along with PRIMARY KEY constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
If the table is already populated it is not possible to change a column to IDENTITY column or convert it to non IDENTITY column. You would need to export all the data out then you can change column type to IDENTITY or vice versa and then import data back.
I know it is painful process but I believe there is no alternative except for using sequence as mentioned in this post.
Be carefull like if you want the ID elements to be contigius or not. As SQLSERVER ID can jump by 1000 .
Examle: before restart ID=11
after restart , you insert new row in the table, then the id will be 1012.
You could do the following: New Table Creation:
-- create new table with Column ID which is Primary Key and Auto Increment --
CREATE TABLE titles(
id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, --Primary Key with Auto-Increment --
keyword VARCHAR(260),
status VARCHAR(10),
);
If you Table Already exists and need to make the changes to ID column to be auto-increment and Primary key, then see below:
ALTER TABLE table DROP COLUMN id; // drop the existing ID in the table
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key

Resources