Add a IDENTITY to a column in SQL SERVER 2008 - sql-server

create table stud(
Student_Id int primary key,
Student_Name varchar(30),
Student_surname varchar(12),
Student_Initial varchar(10))
I had created a table stud. Now i want to add Identity to Student_Id column using alter query
alter table stud alter column student_Id int identity
I get error as
Incorrect syntax near the keyword 'identity'.

ALTER TABLE MyTable
ADD ID INT IDENTITY(1,1) NOT NULL

You cannot make an already existing column as an IDENTITY column. Either you drop and recreate the table with the column marked as IDENTITY', or drop the column and add a newIDENTITY` column.

If Stud contains data, you could always make a shadow table, e.g. Stud2, which contains the Identity column, then run
ALTER TABLE dbo.stud SWITCH TO dbo.stud2
Then you can reseed Stud2, drop Stud, and rename Stud2 to Stud.
That way you can keep the data while dropping/recreating the table with Identity.

Syntax:
IDENTITY [ (seed , increment) ]
alter your table like as this:
create table stud(
Student_Id int IDENTITY(1,1) primary key,
Student_Name varchar(30),
Student_surname varchar(12),
Student_Initial varchar(10));

you can use below query to set identity
CREATE TABLE [dbo].[stud](
[Student_Id] [int] IDENTITY(1,1) NOT NULL,
[Student_Name] [varchar](30) NULL,
[Student_surname] [varchar](12) NULL,
[Student_Initial] [varchar](10) NULL,
PRIMARY KEY CLUSTERED
(
[Student_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

Related

How to alter column from int to Uniqueidentifier in SQL Server 2008

I have a table with column "ID" as datatype int.
CREATE TABLE [dbo].[STUDENT]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[DOB] [datetime] NOT NULL ,
[NAME] [nvarchar](250) NULL,
[CLASS] [nvarchar](50) NULL,
CONSTRAINT [PK_STUDENT_DATA]
PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 95) ON [PRIMARY]
) ON [PRIMARY]
Now I want to change datatype from int to uniqueidentifier. I have deleted constraint PK_STUDENT_DATA. My ALTER statement is
ALTER TABLE dbo.STUDENT COLUMN ID uniqueidentifier
I am getting error:
Identity column 'HISTORY_ID' must be of data type int, bigint,
smallint, tinyint, or decimal or numeric with a scale of 0, and
constrained to be nonnullable.
The identity column is noncompatible with UniqueIdentifier data type Column.So you need to drop the column and create the new column with UniqueIdentifier data type.Since IDENTITY cannot be used with GUID.Use NEWID instead.
Perform Following Steps:
1. Initially, you need to remove the constraint from table
DROP Index [PK_STUDENT_DATA] ON STUDENT
2. After that
ALTER TABLE STUDENT drop COLUMN ID
3. And finally
ALTER TABLE STUDENT
ADD [Id] UNIQUEIDENTIFIER NOT NULL
PRIMARY KEY NONCLUSTERED DEFAULT NEWID()
Please follow below steps:
Firstly, you should remove PrimaryKey in ID column.
Secondly, you should ALTER ID column with [ID] [int] IDENTITY(1,1) NULL and call update command with NULL value.
Thirdly, call command ALTER TABLE dbo.STUDENT COLUMN ID uniqueidentifier NOT NULL and set primary key to this column.
Case 1: If you want to alter colums without constraint
First you need to drop existing column if you want to change from INT To UNIQUEIDENTIFIER. Do this by following way:
ALTER TABLE TableName
DROP COLUMN COLUMN1, COLUMN2 --IF you want multiple/single column
After that you can add columns by following way:
ALTER TABLE TableName
ADD COLUMN1 UNIQUEIDENTIFIER,
COLUMN2 UNIQUEIDENTIFIER
Case 2: If you want to alter colums which contains constraint
Then firstly remove that constraint and do the above steps.

update nvarchar not null field length

I can update the column's length if it in null when created
MYCOLUMN1 nvarchar(12) NULL
My query:
Alter table MYTABLE ALTER Column MYCOLUMN1 nvarchar(13) NULL
but how can I change the length if column is not null?
MYCOLUMN2 nvarchar(12) NOT NULL
Alter table MYTABLE ALTER Column MYCOLUMN2 nvarchar(13) NOT NULL
when I try to do that SQL Server says
Msg 4902, Level 16, State 1, Line 1
Cannot find the object "MYCOLUMN2" because it does not exist or you do not have permissions.
I have permission because i am admin and table's column does exist.
Guys thanks for your response...
Here is table structure
CREATE TABLE [dbo].[MYTABLE](
[MyKey] [int] IDENTITY(1,1) NOT NULL,
[mycolumn1] [nvarchar](12) NULL,
[mycolumn2] [nvarchar](12) NOT NULL,
CONSTRAINT [PK_MYTABLE] PRIMARY KEY CLUSTERED
(
[MyKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Column names are case sensitive. Please try
Alter table MYTABLE ALTER Column [mycolumn2] nvarchar(13) NOT NULL
I've tried and it works fine on sqlserver2012.

Convert INT to BIGINT in SQL Server

SQL 2005, 600,000,000 rows.
I have a table called Location currently using the data type INT in identity PK column LocationID. I would like to attempt converting this data type to BIGINT.
The following script I think should help to allow inserted into the PK column but i am unsure how to progress form here.
SET IDENTITY_INSERT LOCATION ON /*allows insert into the identity column*/`
SET IDENTITY_INSERT LOCATION OFF /*Returns the identity column to initial state*/`
Location table create script below:
CREATE TABLE [dbo].[Location](
[LocationID] [int] IDENTITY(1,1) NOT NULL,
[JourneyID] [int] NULL,
[DeviceID] [int] NOT NULL,
[PacketTypeID] [int] NULL,
[PacketStatusID] [int] NULL,
CONSTRAINT [Location_PK] PRIMARY KEY CLUSTERED
(
[LocationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Location] WITH CHECK ADD CONSTRAINT [Device_Location_FK1] FOREIGN KEY([DeviceID])
REFERENCES [dbo].[Device] ([DeviceID])
GO
ALTER TABLE [dbo].[Location] CHECK CONSTRAINT [Device_Location_FK1]
GO
ALTER TABLE [dbo].[Location] WITH CHECK ADD CONSTRAINT [PacketStatus_Location_FK1] FOREIGN KEY([PacketStatusID])
REFERENCES [dbo].[PacketStatus] ([PacketStatusID])
GO
ALTER TABLE [dbo].[Location] CHECK CONSTRAINT [PacketStatus_Location_FK1]
GO
ALTER TABLE [dbo].[Location] WITH CHECK ADD CONSTRAINT [PacketType_Location_FK1] FOREIGN KEY([PacketTypeID])
REFERENCES [dbo].[PacketType] ([PacketTypeID])
GO
ALTER TABLE [dbo].[Location] CHECK CONSTRAINT [PacketType_Location_FK1]
One option i think would be to copy the data to a new table then delete the old table and rename the new one however we have constraints that will need to be dropped for this to work.
Your idea of a new table is the way to go.
On a development server, you can see the script that SSMS would produce if you change the data type using the table designer. It is a good start. This will add triggers and constraints back afterwards.
A tool like Red gate SQL Compare also allows you to check that everything was created OK

Inserting records in database tables using "inheritance"

I have a table whose primary key is also a foreign key to the primary key of another table (i.e. "inheritance" as simulated in a database).
/****** Object: Table [dbo].[BaseClass] Script Date: 07/15/2011 18:17:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BaseClass](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](50) NOT NULL,
[Description] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_BaseClass] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
USE [TestConcepts]
GO
/****** Object: Table [dbo].[DerivedTable] Script Date: 07/15/2011 18:17:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DerivedTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[SpecialProperty] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_DerivedTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DerivedTable] WITH CHECK ADD CONSTRAINT [FK_DerivedTable_BaseClass] FOREIGN KEY([ID])
REFERENCES [dbo].[BaseClass] ([ID])
GO
ALTER TABLE [dbo].[DerivedTable] CHECK CONSTRAINT [FK_DerivedTable_BaseClass]
GO
What is the proper way to insert records in this situation? Obviously an insert doesn't return the PK of the inserted row (plus the child's table's PK is identity as well).
Here are a few examples of this pattern.
The sub-type table should not have auto-increment ID, the ID matches the one in the super-type table.
The basic technique (using your example) looks something like
DECLARE #MY_ID integer;
INSERT INTO BaseTable(Title, Description)
VALUES ('title_here', 'blah, blah');
SELECT #MY_ID = SCOPE_IDENTITY();
INSERT INTO DerivedTable(ID, SpecialProperty)
VALUES (#MY_ID, newid()); -- the SpecialProperty is uniqueidentifier
One approach is to create a view, one for each sub-type table, or just one over all of them. Then create an INSTEAD OF INSERT TRIGGER on the view and use the technique inside the trigger.
You may also find this technique for capturing multiple inserted IDs useful too.
Nobody calls this "inheritance". That's not what it is. It's a relation, the R in RDBMS.
INSERTs do tell you the PK of the just-inserted row. Look at ##SCOPE_IDENTITY on SQL Server.
The DERIVEDCLASS table could have an auto-incremented (identity) PK but if so there must be another column that is a foreign key reference back to BASETABLE:
BASETABLE
id int pk autoincrement
baseattribute1
baseattribute2
etc etc
DERIVEDTABLE
id int pk autoincrement
**baseid** foreign key references BASETABLE(id)
extendedattribute1
extendedattribute2
This would permit multiple derivations of each base entity. Placing a unique index on DERIVEDTABLE.baseid or making baseid the PK would prevent this, if that is desired.
The following would instantiate the members of the base class and their derived instances and/or extended properties if any [which it is will depend on whether baseid has unique constraint in DerivedTable; if the latter it could be the PK in a one-to-one relationship with BaseTable, rather than a many-to-one]:
select * from BASETABLE
LEFT JOIN DERIVEDTABLE
on BASETABLE.id = DERIVEDTABLE.baseid
Instances of the base class that have not been extended will have NULL in the extendedattribute columns.
To find only those entities that have been extended use an inner join:
select * from DERIVEDTABLE
inner join BASETABLE
on DERIVEDTABLE.baseid = BASETABLE.id

SQL Server won't let me make column identity

So I have a table in SQL Server w/ a primary key column, and 4 other columns. When I modify the table, and select the primary key column to be identity, it won't let me save the table.
How can I make it an identity column through T-SQL or something without going to the UI?
Thanks.
Here's the create
USE [db]
GO
/****** Object: Table [dbo].[tblMessages] Script Date: 04/05/2011 11:58:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tblMessages](
[messageId] [int] NOT NULL,
[messageText] [varchar](500) NOT NULL,
[messageLatitude] [float] NOT NULL,
[messageLongitude] [float] NOT NULL,
[messageTimestamp] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
[messageId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
You cannot turn an existing column into an IDENTITY column after it's been created.
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumn INT IDENTITY
will cause an error:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword
'IDENTITY'.
You need to create a new column of type INT IDENTITY and then possibly drop the old one. Or if your table is still empty: drop it and re-create it with the correct settings for your ID column
ALTER TABLE MyTable
ADD NewIdentity INT IDENTITY;
ALTER TABLE MyTable
DROP COLUMN OldPK;
EDIT
If your table is empty, just drop it and add IDENTITY after INT on your PK column and be done with it.

Resources