Set IDENTITY to begin with Alphabets - sql

I have created a table and set its PK to IDENTITY(1,1).
But I want the PK to begin/start with alphabets e.g CRMSON0, CRMSON1, CRMSON2... and so on.
But I wasn't able to find the solution for Microsoft SQL Server.
on Microsoft website, details I could find were about IDENTITY(seed,increment) or IDENTITY(data type,seed,increment).
Can anyone suggest?

You can create computed column composed from CRMSON + ID value:
CREATE TABLE #table1 (ID INT IDENTITY(0,1)
,col INT
,col_pk AS CONCAT('CRMSON', ID) PRIMARY KEY);
INSERT INTO #table1(col) VALUES(3), (4);
SELECT *
FROM #table1;
LiveDemo

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,
CrimsonID AS 'CRIMSON' + CAST(ID AS VARCHAR(10) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into YourTable without specifying values for ID or CrimsonID:
INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and CrimsonID will contain values like Crimson1, Crimson2,...... and so on - automatically, safely, reliably, no duplicates.
That'll work fine - but as others have already pointed out - I would NOT recommend using this column as the clustered, primary key - use the ID column for that, it's ideally suited for such a task! The CrimsonID is bad for mainly two reasons: it's a variable length string, and it's much too wide compared to an int

Related

Auto increment primary key in SQL Server (long unique code)

I need add new column in to DB table but with auto increament (primary key). I could use this:
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)
but this creates unique integers 1, 2, 3, etc But i would like create long uniques numbers exmpl: 0542365 or with letters A546980 it is posible?
One way to reliably and nicely do this:
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,
AlphaID AS 'A' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into YourTable without specifying values for ID or AlphaID:
INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and AlphaID will contain values like A0000001, A0000002,...... and so on - automatically, safely, reliably, no duplicates.

How to Paste desired selection in SQL Server 2008

So I have a problem, I was wondering is there a way of inserting the (ID VALUES) to each column since I forgot. I have a really long code. Is there a way for me to select a piece of code to paste the number ID values or a Method of some sort? Or is my only option to do it manually?
CREATE TABLE tASTON
(AsM_ID int Primary Key Not Null IDENTITY(1,1),Make Nvarchar(50), Model nvarchar (50))
Insert into tASTON(AsM_ID,Make,Model) Values ('Aston Martin','DB4')
Insert into tASTON (AsM_ID,Make,Model) Values ('Aston Martin','DB5')
Insert into tASTON (AsM_ID,Make,Model) Values ('Aston Martin','DB6')
Insert into tASTON (AsM_ID,Make,Model) Values ('Aston Martin','DB7')
Insert into tASTON (AsM_ID,Make,Model) Values ('Aston Martin','Vanquish') etc...
Seeing it's an IDENTITY column, there's no need to manually INSERT values. This ought to work:
Insert into tASTON(Make,Model) Values ('Aston Martin','DB4')
Update: Removed brand, as it was confusing and a mistake on my part. Replaced Brand with Make, instead.*
Unrelated, but judging by the name of the table, are you really creating one table per brand of car? If so, I'd suggest creating a make and a car table, where you then implement a key relationship between tCar and tMake:
CREATE TABLE tCAR
(
CAR_ID int Primary Key Not Null IDENTITY(1,1)
, MAKE_ID int FOREIGN KEY REFERENCES tMake(MAKE_ID)
, Model nvarchar (50)
)

Insert and alter in one statement

I'd like to store a set of data into a database but if it's a pre-existing record, I'd like to alter it. Otherwise, create a new one. Is there a combine statement for that? (Haven't got any when googling.)
Right now, the best I have is to check if already exists and then perform one of the operations. Seems cumbersome to me.
create table Stuff (
Id int identity(1001, 1) primary key clustered,
Beep int unique,
Boop nvarchar(50))
IN MYSQL :
You may use INSERT ... ON DUPLICATE KEY UPDATE .
eg:
INSERT INTO table (a,b,c) VALUES (4,5,6)
ON DUPLICATE KEY UPDATE c=9;
For more information: http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
MySQL uses INSERT... ON DUPLICATE KEY and MSSQL uses MERGE
MERGE is supported by Azure, and I can highly recommend this blog article on it, as a good intro to the statement
Here is a merge statement based on the schema provided...
create table #Stuff (
Id int identity(1001, 1) primary key clustered,
Beep int unique,
Boop nvarchar(50),
Baap nvarchar(50)
);
INSERT INTO #Stuff VALUES (1,'boop', 'poop');
INSERT INTO #Stuff VALUES (2,'beep', 'peep');
SELECT * FROM #STUFF;
MERGE #Stuff
USING (VALUES(1,'BeepBeep','PeepPeep')) AS TheNewThing(A,B,C)
ON #Stuff.Beep = TheNewThing.A
WHEN MATCHED THEN UPDATE SET #Stuff.Boop = TheNewThing.B, #Stuff.Baap = 'fixed'
WHEN NOT MATCHED THEN INSERT (Beep,Boop,Baap) VALUES (
TheNewThing.A, TheNewThing.B, TheNewThing.C);
SELECT * FROM #STUFF
I also found a really good SO Q which might make good further reading
yes you can easily do it using pl/sql here is sample code which will help you
http://docs.oracle.com/cd/B10501_01/appdev.920/a96624/01_oview.htm#7106

Zero As Primary Key In SQL Server 2008

Is it possible to insert 0 in the primary key field of a table in SQL server 2008?
As long it's a numeric field, yes... follow along at home!
create table TestTable
(
TestColumn int not null primary key
)
insert TestTable values(0)
The primary key restriction only requires that the value be unique and the column not be nullable.
For an identity field:
create table TestTable
(
TestColumn int identity(1, 1) not null primary key --start at 1
)
set identity_insert TestTable on
insert TestTable (TestColumn) values (0) --explicitly insert 0
set identity_insert TestTable off
The identity(1, 1) means "start at one and increment by one each time something is inserted". You could have identity(-100, 10) to start at -100 and increment by 10 each time. Or you could start at 0. There's no restriction.
You can generally answer questions like these for yourself by just trying them and seeing if they work. This is faster and usually more beneficial than asking on StackOverflow.
Yes, it can be zero. The value can be from −2,147,483,648 to 2,147,483,647, from −(2^31) to 2^31 − 1, the full range of an unsigned integer.
If you expect a lot of records, like up to 4.3 billion, it makes sense to start from the smallest value, and work your way up.
CREATE TABLE TestTable
(
TestColumn INT IDENTITY(−2,147,483,648, 1) NOT NULL PRIMARY KEY --start at 1
)

How do I insert into a table and get back the primary key value?

I have a primary key set up to auto increment.
I am doing multiple queries and I need to retrieve that primary key value to use as a foreign key in another table (IsIdentity = TRUE).
Is there any elegant way to get back the primary key value when I do an insert query? Right now I am requerying and getting the highest value in that column which seems really hacky.
Any suggestions?
If you are using SQL Server 2005 or later, you can use the OUTPUT clause.
create table T(
pk int identity primary key,
dat varchar(20)
);
go
insert into T
output inserted.pk
values ('new item');
go
drop table T;
The output can be directed to a table as well as to the client. For example:
create table T(
pk int identity primary key,
dat varchar(20)
);
create table U(
i int identity(1001,1) primary key,
T_pk int not null,
d datetime
);
go
insert into T
output inserted.pk, getdate()
into U(T_pk,d)
values ('new item'), ('newer item');
go
select * from T;
select * from U;
go
drop table T, U;
Beginning with SQL Server 2008, you can use "composable DML" for more possibilities.
insert into YourTable values (...)
get the new PK with scope_identity()
select scope_identity()
INSERT INTO YourTable (1, 2, etc.)
OUTPUT inserted.yourIDcolumn
VALUES (value1, value2, value...)
Note: This is for MS SQL 2005 and greater
SCOPE_IDENTITY() is probably what you want. It returns the ID of the last record inserted by the same code context in which it executes.
IDENT_CURRENT('tablename') is subject to concurrency issues. That is, there's no guarantee that another record won't be inserted between the INSERT and the call to IDENT_CURRENT.
I must confess, I'm not sure to what source of amazement the VillageIdiot's outburst refers, but I myself am quite astonished that this question does not appear to be a duplicate at all.
holy crap!!!
just call SCOPE_IDENTITY() function:
insert into your_talble(col1,col2) values('blah','more blah')
select scope_identity()
because selecting highest value will return error if any other statement make an insert. the function scope_identity() returns the identity created in current context (that is by your statement)
You should use scope_identity(). And I recommend to wrap insert statement and scope_identity() into transaction.