How to auto increment in vb form - sql-server

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.

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.

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

Storing hex equivalent in identity column in sql

Just as the title says, if I have a table has a struct like this
create table myTable
(
ID int identity(1,1) not null,
col1 varchar(20) not null,
col2 varchar(20) not null
constraint pk_myTable primary key (ID)
)
If I insert some value in this table it would automatically take value in col ID. I wanna know is a way I could get SQL Server to store hex equivalent in the column. Say, for 1, it should store 0x01 2 as 0x02... 10 as 0xA and so on?
I don't wanna know any tricks or something, I know I can create this this col as varchar and then create a procedure for insert, or create a trigger for insert, that would do the required transformation and would produce the desired result, that's not a big issue.
But what I wanna know is there a inbuilt function/procedure/trigger that would help me achieve what I am trying to achieve? Not necessarily in SQL Server 2008, but may be in 2012, does there exists anything like this?
I agree with Joe Stefanelli and Habo above that you don't need do do this. That said the technique is usefull in other scenarios.
Define your table like this (note the computed column)
CREATE TABLE mytable(
ID int identity(1,1) not null,
col1 varchar(20) not null,
col2 varchar(20) not null,
ComputedHexColumn AS CONVERT(VARBINARY(8), ID),
CONSTRAINT pk_myTable PRIMARY KEY CLUSTERED(ID)
)
Then populate it
INSERT INTO mytable(col1,col2)
SELECT 'col1 - 1','col2 - 1'
UNION SELECT 'col1 - 2','col2 - 2'
UNION SELECT 'col1 - 3','col2 - 3'
UNION SELECT 'col1 - 4','col2 - 4'
then anytime you select from the table it will include the hex value
SELECT * FROM mytable
In cases where the computed value was much more expensive to calculate then you can mark the column as PERSISTED. The database will then physically store the value and update it when appropriate.

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.

SQLServer IDENTITY Column with text

How would I create an IDENTITY column in SQLServer with text in the column?
Example:
ABCD-987065
ABCD-987066
ABCD-987067
In addition to the other answers, you could create a computed column on the table to provide what you are asking for.
CREATE TABLE dbo.MyTable
(
Id int NOT NULL PRIMARY KEY,
CombinedId AS 'ABCD-' + CAST(Id as varchar(16))
)
Or:
CREATE TABLE dbo.MyTable
(
Id int NOT NULL PRIMARY KEY,
PrefixField varchar(16),
CombinedId AS PrefixField + CAST(Id as varchar(16))
)
(Your question doesn't say whether the prefix is intended to be fixed or not...)
You'd have to not use an IDENTITY column, but generated the ids/strings yourself.
Far better to format the IDENTITY column for display instead, especially if the string part is constant for all records - makes indexing/querying more performance and saves on db space.
If records may have a different string section (i.e. not all starting with "ABCD-"), then you could store that as a separate field.
You could increment your string values with a function like this:
http://www.sqlservercentral.com/scripts/Miscellaneous/31448/
I'm curious, though, why you're looking to use an alpha-numeric key rather than just a numeric one.
CREATE TABLE BikeParts (
BikeParts_GUID AS 'ABCD-' + RIGHT(REPLICATE('0', 8) + CONVERT(VARCHAR, BikePart_ID), 10),
BikePart_ID INT IDENTITY(1, 1),
BikePart_Name VARCHAR(100)
)
INSERT INTO BikeParts VALUES ('Break Cable')
INSERT INTO BikeParts VALUES ('Seat Cover')
INSERT INTO BikeParts VALUES ('Head Light')
INSERT INTO BikeParts VALUES ('Tail Lamp')
SELECT * FROM BikeParts
No. The actual column type must be an int or bigint works too.
Nope, sorry. The identity "property" can only be placed on columns with the integer or decimal data type.
No but you can create your Select statement in such a way as to return the code you want:
Select 'ABCD-' + Cast(IdColumn as varchar) as IdColumn From MyTable Where (....);
This assumes that you have a column called IdColumn in your table and that the "IDENTITY" property has been set to "true". That is, highlight the field in the table designer of SQL Server Management Studio and you'll see a window for the properties at the bottom.
If the 'ABCD' part may change, you could place this value in another field and then retrieve as so:
Select PrefixField + '-' + Cast(IdColumn as varchar) as IdColumn From MyTable Where (....);
You could, of course, create a View to do this for you or even a computed field as well. That way, the return value is built in to the query and you don't have to remember to enter all of this each time.
Check the answers here...
Increasing Alphanumeric value in user defined function

Resources