SQLServer IDENTITY Column with text - sql-server

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

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.

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.

In TSQL can I create a UDF which has as input a table's row?

I'm looking to create what I would think is simple.
I want a user defined function which takes a row from a table as imput and returns a scalar value.
Something like
select
mt.Id,
MyUDF(mt)
from M
MyTable mt
where mt.Price > 0
I understand that I can pass in the Id to the UDF, and then lookup the values from within the UDF, but that seems like a lot of extra work.
No, a RDBMS has no concept of a row as a whole - only a tuple of fields. You need to either send the individual fields separately, or send an ID which can be used inside the UDF to retrieve the fields necessary from that row.
As marc_s said, the idea of sending a "row" as an object in T-SQL isn't present. You can send the data from the row as individual values, but not the row itself.
A computed column on the table itself would probably make more sense. If the value is directly dependent on the values present in the row (and not dependent on any external values), then this would be a solution.
For example, say I have this table:
Customer:
CustomerID
FirstName
LastName
...
If I wanted a computed column for FullName, my table declaration would look like:
create table Customer
(
CustomerID int identity(1, 1) primary key,
FirstName varchar(100),
LastName varchar(100),
FullName as LastName + ', ' + FirstName
)
I could also add it after the fact with an ALTER statement
alter table Customer add FullName as LastName + ', ' + FirstName

Resources