How to alter column from int to Uniqueidentifier in SQL Server 2008 - sql-server

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.

Related

Make a "normal" table as temporal table

I have a table created like this:
CREATE TABLE address_user
(
[username] VARCHAR(13) NOT NULL,
[address] CHAR(58) NOT NULL,
[id] BIGINT NOT NULL,
CONSTRAINT [PK_ address_user]
PRIMARY KEY CLUSTERED ([id] ASC)
);
Now I want to be able to keep the history modification of this table, so I want to make it as temporal table. I know the script to create a temporal table, the final result should be:
CREATE TABLE address_user
(
[username] VARCHAR(13) NOT NULL,
[address] CHAR(58) NOT NULL,
[id] BIGINT NOT NULL,
[sys_start_time] DATETIME2(7)
GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
[sys_end_time] DATETIME2 (7)
GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,
PERIOD FOR SYSTEM_TIME ([sys_start_time], [sys_end_time]),
CONSTRAINT [PK_ address_user]
PRIMARY KEY CLUSTERED ([id] ASC)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[address_user_history], DATA_CONSISTENCY_CHECK=ON));
The easy way to do that is just delete the previous table, and recreate the table with the good schema.
However, I have a lot of information in my table, save the data and delete the table, recreate it and re-insert the data make me uncomfortable.
So if you have a solution to transform the first table in temporal table without the need to delete everything and recreate it, it should be a great help!
Create the new table address_user_new, insert the data, then use sp_rename to rename address_user to address_user_old and address_user_new to address_user. This can all be done in a transaction to ensure ensure that the transition is atomic and apparently-instantaneous. eg
if object_id('address_user') is not null
ALTER TABLE address_user SET ( SYSTEM_VERSIONING = OFF)
go
if object_id('address_user_new') is not null
ALTER TABLE address_user_new SET ( SYSTEM_VERSIONING = OFF)
go
drop table if exists address_user
drop table if exists address_user_history
drop table if exists address_user_new
drop table if exists address_user_old
go
CREATE TABLE address_user
(
[username] VARCHAR(13) NOT NULL,
[address] CHAR(58) NOT NULL,
[id] BIGINT NOT NULL,
CONSTRAINT [PK_address_user]
PRIMARY KEY CLUSTERED ([id] ASC)
);
go
CREATE TABLE address_user_new
(
[username] VARCHAR(13) NOT NULL,
[address] CHAR(58) NOT NULL,
[id] BIGINT NOT NULL,
[sys_start_time] DATETIME2(7)
GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
[sys_end_time] DATETIME2 (7)
GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,
PERIOD FOR SYSTEM_TIME ([sys_start_time], [sys_end_time]),
CONSTRAINT [PK_address_user_new]
PRIMARY KEY CLUSTERED ([id] ASC)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[address_user_history], DATA_CONSISTENCY_CHECK=ON));
go
set xact_abort on
begin transaction
insert into address_user_new(username,address,id)
select username,address,id
from address_user with (tablockx)
exec sp_rename 'address_user', 'address_user_old', 'OBJECT'
exec sp_rename 'PK_address_user', 'PK_address_user_old', 'OBJECT'
exec sp_rename 'address_user_new', 'address_user', 'OBJECT'
exec sp_rename 'PK_address_user_new', 'PK_address_user', 'OBJECT'
commit transaction

Add a IDENTITY to a column in SQL SERVER 2008

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

How to set identity column to created table in SQL server

I created a table in SQL Server like this:
CREATE TABLE [UserName]
(
[ID] [int] NOT NULL ,
[Name] [nvarchar] (50) NOT NULL ,
[Address] [nvarchar] (200) NULL
CONSTRAINT [PK_UserName] PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY]
GO
If I want to make ID an identity column, what do I need? Do I need to drop and create this table and set ID to [ID] [int] IDENTITY(1,1) NOT NULL .
By using drop and create, all of data from UserName table are lost .
Is there another way to set IDENTITY COLUMN to created table's column without losing data?
I use SQL Server 2008 R2 :)
ALTER TABLE [UserName] DROP COLUMN [ID];
ALTER TABLE [UserName]
ADD [ID] integer identity not null;
Try this one -
DECLARE #temp TABLE
(
ID INT NOT NULL
, Name NVARCHAR(50) NOT NULL
, [Address] NVARCHAR(200) NULL
)
INSERT INTO #temp (ID, Name, [Address])
SELECT ID, Name, [Address]
FROM dbo.UserName
DROP TABLE dbo.UserName
CREATE TABLE dbo.UserName
(
[ID] [int] IDENTITY(1,1) NOT NULL
, [Name] [nvarchar] (50) NOT NULL
, [Address] [nvarchar] (200) NULL
CONSTRAINT [PK_UserName] 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]
SET IDENTITY_INSERT dbo.UserName ON
INSERT INTO dbo.UserName (ID, Name, [Address])
SELECT ID, Name, [Address]
FROM #temp
SET IDENTITY_INSERT dbo.UserName OFF
The easiest way:-
Right click on the table in object explorer and select 'Design'
Select the column for which you want to set identity and go to Column Properties
Under 'Identity Specification' change '(Is Identity)' to 'Yes'
Click Save.... Done :)
Hope This Helps
Here is a solution that is minimally logged.
SELECT
IDENTITY(INT, 1,1) AS ID,
Name, [Address]
INTO dbo.UserName_temp
FROM dbo.UserName;
ALTER TABLE dbo.UserName_temp
ADD CONSTRAINT [PK_UserName] PRIMARY KEY CLUSTERED;
DROP TABLE dbo.UserName;
EXEC sp_rename 'dbo.UserName_temp', 'UserName';
SRC:
http://sqlmag.com/sql-server/appending-identity-column-temporary-table
But the IDENTITY() function can "only in a SELECT statement with an INTO table clause."
http://msdn.microsoft.com/en-us/library/ms189838.aspx

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

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