generate sequence in sql server 2014 - sql

I am trying to generate a sequence varchar text type, but I do not want to have to create another column to get the id to format it and insert it I want to generate it in the same column, help
create table tbl (
Id int identity not null,
CusId as 'CUS' + format(Id, '00000'),
-- ...
)

You can use sequence object that appeared in SQL Server 2012 + default value like this:
create sequence dbo.ids as int
minvalue 1;
create table dbo.tbl (
CusId varchar(100) default 'CUS' + format(NEXT VALUE FOR dbo.ids, '00000'));
insert into dbo.tbl (CusId) default values;
insert into dbo.tbl (CusId) default values;
insert into dbo.tbl (CusId) default values;
select *
from dbo.tbl;
-----
--CusId
--CUS00001
--CUS00002
--CUS00003

Believe the only viable solution is using 2 columns as you mentioned, and discussed here:
Autoincrement of primary key column with varchar datatype in it
Have not seen it achieved in a single column on its own.

Related

default column value

i'm trying to have a table with a column that has a default value.
right now i can only get this by having a trigger change the value to the default, is it possible to have it declared on the table right from the start?
Would it be possible to have something like the Identity, where i don't have to pass the value into the insert?
egx: insert into Direct values(2)
and the table would become
id | item
1 | 2
the id = 1, would be the deafult value
thanks in advance!
you can create constraints at time of table creation or later.
create table
#test
(
id int identity(1,2),
name char(255) default newid(),
code int default 2
)
---if a table contains all default values,you can insert like below
insert into #test
default values
updated as per comments:
create table
#test1
(
id int identity(1,2),
name char(255) default newid(),
code int default 2,
notdf int
)
---if a table contains one default value and rest all are default
insert into #test1(notdf)
select 2
Further if you want to add a default value after table creation you can do it like below
create table
tt1
(
valuue int,
address char(2) not null
)
insert into tt1
select 1,'a'
ALTER TABLE tt1 ADD CONSTRAINT test1 DEFAULT null FOR address;
Use default. You can change an existing column by doing:
ALTER TABLE t ADD CONSTRAINT df_t_column DEFAULT 1 for id;
An identity is trickier. I would suggest copying the data over to a temporary table, dropping the table, creating it with an identity column and reloading the data.

Set IDENTITY to begin with Alphabets

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

SQL Server Database unique number generation on any record insertion

I have like 11 columns in my database table and i am inserting data in 10 of them. i want to have a unique number like "1101 and so on" in the 11th column.
Any idea what should i do?? Thanks in advance.
SQL Server 2012 and above you can generate Sequence
Create SEQUENCE RandomSeq
start with 1001
increment by 1
Go
Insert into YourTable(Id,col1...)
Select NEXT VALUE FOR RandomSeq,col1....
or else you can use Identity
Identity(seed,increment)
You can start the seed from 1101 and increment the sequence by 1
Create table YourTable
(
id INT IDENTITY(1101,1),
Col varchar(10)
)
If you want to have that unique number in a different field then you can manipulate that field with primary key and insert that value.
If you want in primary key value, then open the table in design mode, go to 'Identity specification', set 'identity increment' and 'identity seed' as you want.
Alternatively you can use table script like,
CREATE TABLE Persons
(
ID int IDENTITY(12,1) PRIMARY KEY,
FName varchar(255) NOT NULL,
)
here the primary key will start seeding from 12 and seed value will be 1.
If you have your table definition already in place you can alter the column and add Computed column marked as persisted as:
ALTER TABLE tablename drop column column11;
ALTER TABLE tablename add column11 as '11'
+right('000000'+cast(ID as varchar(10)), 2) PERSISTED ;
--You can change the right operator value from 2 to any as per the requirements.
--Also replace ID with the identity column in your table.
create table inc
(
id int identity(1100,1),
somec char
)

SQL attribute (column) value contstraint

I'm using sqlite as my database. I need a attribute to be limited to values of 0 or 1.
Is it possible to specify this in the definition of the table?
CREATE TABLE yourTable
( id INT Primary key
, onefield INT CHECK(onefield IN (0,1)) ---the limited field/attribute
)

Can a sql server table have two identity columns?

I need to have one column as the primary key and another to auto increment an order number field. Is this possible?
EDIT: I think I'll just use a composite number as the order number. Thanks anyways.
CREATE TABLE [dbo].[Foo](
[FooId] [int] IDENTITY(1,1) NOT NULL,
[BarId] [int] IDENTITY(1,1) NOT NULL
)
returns
Msg 2744, Level 16, State 2, Line 1
Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed.
So, no, you can't have two identity columns. You can of course make the primary key not auto increment (identity).
Edit: msdn:CREATE TABLE (Transact-SQL) and CREATE TABLE (SQL Server 2000):
Only one identity column can be created per table.
You can use Sequence for second column with default value IF you use SQL Server 2012
--Create the Test schema
CREATE SCHEMA Test ;
GO
-- Create a sequence
CREATE SEQUENCE Test.SORT_ID_seq
START WITH 1
INCREMENT BY 1 ;
GO
-- Create a table
CREATE TABLE Test.Foo
(PK_ID int IDENTITY (1,1) PRIMARY KEY,
SORT_ID int not null DEFAULT (NEXT VALUE FOR Test.SORT_ID_seq));
GO
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
SELECT * FROM Test.Foo
-- Cleanup
--DROP TABLE Test.Foo
--DROP SEQUENCE Test.SORT_ID_seq
--DROP SCHEMA Test
http://technet.microsoft.com/en-us/library/ff878058.aspx
Add one identity column and then add a computed column whose formula is the name of the identity column
Now both will increment at the same time
No it is not possible to have more than one identity column.
The Enterprise Manager does not even allow you to set > 1 column as identity. When a second column is made identity
Also note that ##identity returns the last identity value for the open connection which would be meaningless if more than one identity column was possible for a table.
create table #tblStudent
(
ID int primary key identity(1,1),
Number UNIQUEIDENTIFIER DEFAULT NEWID(),
Name nvarchar(50)
)
Two identity column is not possible but if you accept to use a unique identifier column then this code does the same job as well. And also you need an extra column - Name column- for inserting values.
Example usage:
insert into #tblStudent(Name) values('Ali')
select * from #tblStudent
Ps: NewID() function creates a unique value of type uniqueidentifier.
The primary key doesn't need to be an identity column.
You can't have two Identity columns.
You could get something close to what you want with a trigger...
in sql server it's not possible to have more than one column as identity.
I've just created a code that will allow you inserting two identities on the same table. let me share it with you in case it helps:
create trigger UpdateSecondTableIdentity
On TableName For INSERT
as
update TableName
set SecondIdentityColumn = 1000000+##IDENTITY
where ForstId = ##IDENTITY;
Thanks,
A workaround would be to create an INSERT Trigger that increments a counter.
So I have a table that has one identity col : applicationstatusid. its also the primary key.
I want to auto increment another col: applicationnumber
So this is the trigger I write.
create trigger [applicationstatus_insert] on [ApplicationStatus] after insert as
update [Applicationstatus]
set [Applicationstatus].applicationnumber =(applicationstatusid+ 4000000)
from [Applicationstatus]
inner join inserted on [applicationstatus].applicationstatusid = inserted.applicationstatusid