SQL Server : identity and autoincrement for varchar - sql-server

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.

Related

MS SQL insert into auto increment column default value

I am creating a database interface to make some basic operations on tables.
CREATE TABLE products (
ID int IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(20)
)
As long as I have been using MySQL database, it worked correctly to insert DEFAULT value onto 'ID' column
INSERT INTO products (ID, Name) VALUES (DEFAULT, "ProductName")
But MS SQL won't let me do that, the error I get is DEFAULT or NULL are not allowed as explicit identity values..
I have been looking for solutions and couldn't find one - is there a way to include ID in the list of columns in the insert statement, but actually let the database handle the value to be inserted(auto-increment value)?
The answer to just not include ID in the list of columns is not solving my problem, as I access the database from a C++ program and try to do it as abstract as possible (and some different tables don't have auto-increment on ID)
Two solution :
ignore the ID column in the column list :
INSERT INTO products (Name) VALUES ('ProductName');
do not specify the column list if you want to insert in all columns except identity :
INSERT INTO products VALUES (DEFAULT, ProductName);
By the way, double quote must never be used for strings but only simple quote. Double quote is reserved for "abnormal" objest names...
You must be define the Id column like this:
[id] [int] IDENTITY(1,1) NOT NULL

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.

Autoincrement of primary key column with varchar datatype in it

CREATE TABLE Persons
(
P_Id varchar(6) NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
in this table P_Id is the primary key. We want to generate autoincrement of P_Id with default value (PN00) in the start while inserting only LastName and FirstName .eg :-PN001 for first entry ,PN002 for second,PN003 for third and so on .
The only viable 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.Persons
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
P_ID AS 'PN' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into Persons without specifying values for ID or P_ID:
INSERT INTO dbo.Persons(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and P_Id will contain values like PN00001, PN00002,...... and so on - automatically, safely, reliably, no duplicates.
There are different ways to address your issue.
You could use a Trigger.Triggers are activated on some events. You could create a trigger for 'Instead of Insert On Persons' event. When the event is triggered, then generate a new P_Id. Insert this new P_Id alongwith all the values as the new record for your table.
This approach wont have coupling with the table's schema.
Refer this link for more information on Triggers :
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
Refer this link to emulate 'before insert trigger' in SQL Server:
How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritence) entities?
You could also use a Procedure like :
create procedure Persons_insert(#lastname varchar(255), #firstname varchar(255))
as
begin
--write code to generate the ID as you like
insert into Persons(p_id,lastname,firstname)values(generated_id,lastname,firstname);
end

Inserting concatenate Identity column with other column

I have a identity column and i have other column while inserting a new row in
table i need to insert into third column with concatenate of two columns result
For reference please see below table
------------------------------------------------
A | B | c
----------------------------------------------
1 | 33 | 133(1 [identity result] + 33)
2 | 112 | 2112
Please help me to solve this issue.
There is already an answer to this question but i think is not the best way to achieve it.
Here's an example on how to achieve it with a computed column.
CREATE TABLE dbo.calculatedTEST (
A INT IDENTITY(1,1) NOT NULL,
B INT NOT NULL,
c AS CONVERT(INT,CONVERT(VARCHAR(max),A)+CONVERT(VARCHAR(max),B))
)
insert into dbo.calculatedTEST
(B)
values
(1),
(1),
(2),
(2)
select * from dbo.calculatedTEST
A computed column is computed from an expression that can use other
columns in the same table. The expression can be a noncomputed column
name, constant, function, and any combination of these connected by
one or more operators. The expression cannot be a subquery.
Unless otherwise specified, computed columns are virtual columns that
are not physically stored in the table. Their values are recalculated
every time they are referenced in a query. The Database Engine uses
the PERSISTED keyword in the CREATE TABLE and ALTER TABLE statements
to physically store computed columns in the table. Their values are
updated when any columns that are part of their calculation change. By
marking a computed column as PERSISTED, you can create an index on a
computed column that is deterministic but not precise. Additionally,
if a computed column references a CLR function, the Database Engine
cannot verify whether the function is truly deterministic. In this
case, the computed column must be PERSISTED so that indexes can be
created on it. For more information, see Creating Indexes on Computed
Columns.
Don't need to insert Column C, You can easily get Column C using Select Statement.
like this.
select A,B,cast(Cast(A as varchar(max))+cast(B as varchar(max)) as
varchar(max)) as C from Your_Table_Name
If you really need to insert column C, then you have to run insert and Update query at the same time to inset value in the C column of the table.
Like:
insert into Table_Name(B) values('33');Select IDENT_CURRENT();
--you'll get the inserted Identity.
--now run the Update query for Identity you get from the insert query.
Sample.
create table #tab1
(
Id bigint identity(1,1) primary key,
a int,
b varchar(50)
)
insert into #tab1(a) values(88);
declare #id1 as bigint set #id1=(select SCOPE_IDENTITY());
update #tab1 set b=cast(id as varchar(max))+cast(a as varchar(max)) where Id=#id1

SQL Server: Auto increment char pk

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.

Resources