Is there any way to auto-generate a specific length column in SQL Server?
For example I want that a specific column default value will be a 12 digit unique number.
You can have an BIGINT IDENTITY column that will generate unique BIGINT values - but they're not 12 digits by default....
Of course, based on a BIGINT IDENTITY, you could create a computed column something like this:
ALTER TABLE dbo.YourTable
ADD AutoField AS 'XY' + RIGHT('0000000000' + CAST(ID AS VARCHAR(10)), 10) PERSISTED
This way, you'd get values of 1, 2, 3, 4 in ID (as identity values), and XY0000000001, XY0000000002, and so forth in your computed AutoField column automatically.
That's pretty much the only "automatic" generation I know of (except for GUID's - but those are longer than 12 chars and not numeric).
What are you trying to do here'?
You can use a bigint identity with seed value 100000000000
create table T (id bigint identity(100000000000, 1), Col1 varchar(50))
And use a check constraint to prevent you from going to far.
alter table T with check add constraint CK_T_ID check (id<1000000000000)
Related
I am creating a table in SQL Server with three columns. I want the first two columns to increment counts one by one. I used the first column as identity column that automatically increments 1 when row is inserted. I tried to do the same with second column (but SQL Server does not allow two identity columns per table). I found another way i-e using Sequence but since I am using SQL Server 2008, it does not have this feature.
How can I achieve my task?
I am using the first identity column in reports and I reset it when some count is achieved; for example when it reaches 20, I reset it to 1 (Edited). The second incremental column will be used by me for sorting the data and i do not intend to reset it.
create table tblPersons
(
IDCol int primary key identity(1,1),
SortCol int primary key identity(1,1),
Name nvarchar(50)
)
PS : I cannot copy the values of IDCol to SortCol because when I reset the IDCol to 20 from my code, the SortCol will copy the same values (instead it should continue to 21,22,23 and so on)
If you plan on incrementing both columns always at the same time, then one workaround here might be to just use a single auto increment column, but use the remainder of that counter divided by 20 for the second value:
CREATE TABLE tblPersons (
IDCol int PRIMARY KEY IDENTITY(1,1),
Name nvarchar(50)
)
SELECT
IDCol,
IDCol % 20 AS SortCol -- this "resets" to zero upon reaching 20
FROM tblPersons;
As an alternative solution, you can use Computed Column
create table tblPersons
(
SortCol int primary key identity(1,1),
IDCol AS CASE WHEN (SortCol % 20) = 0 THEN 20 ELSE (SortCol % 20) END ,
Name nvarchar(50)
)
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
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
)
I have a column in my database. How do i insert an incremented number via an insert so it fills it every row?
Use Identity column
Suppose you want Column Id to be incremented automatically a row is inderted define it as identity
ID INT IDENTITY (1,1)
First 1 is starting value second 1 is seeding it means increment by which integer
in this case the value will start at 1 and increment by 1 every time u insert a new row.
Please let me know if any further help needed
You may go to the designer of the table add a new Column and then go to the properties tab for the column and set
Identity Specification
IsIdentity :Yes
Identity Increment : 1
Identity Seed : 1
Identity Increment sets the number that will be added each time you insert a row. If it was 10 then you would have ids like 10, 20, 30.
Identity Seed is an offset you may need to add (which is the first number to appear) If it was 10 then your first Id would be 10.
Set identity seed for the column you want to increment the value
Alter Table Names Add Id_new Int Identity(1, 1) Go
Alter Table Names Drop Column ID Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
When creating a new table, set the Data Type field to int and de-select Allow Nulls for that column.
Then, in column Properties, expand Identity Specification and change (Is Identity) to Yes.
By default the Identity Increment should be set to 1.
Make that column identity while creating the table which will auto increment that column for each row. You don't have to do explicit insert.
Create auto increment for that column for example
CREATE TABLE table_name
(
id int NOT NULL IDENTITY (1, 1),
name varchar(50) NULL
) ON [PRIMARY]
In the above example column id is auto increment. After each insert its value will increment by 1.
If you want to change that increment number later, please check
Reset AutoIncrement in SQL Server after Delete
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