SQL Server won't let me make column identity - sql-server

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.

Related

Deleting records using DeleteAllOnSubmit not working with FK contstraints

Im trying to use Linqpad so as to use LINQ instead of TSQL when trying to remove some records from a table that is part of a "dependency tree" that spans probably 10-12 tables. So I created some tables in a test db and im experimenting with the DeleteAllOnSubmit and SubmitChanges methods.
I get an FK error. Yet, Im deleting the child objects first. How do I delete when there is FK relations (without using cascading on the FK's)?
The DELETE statement conflicted with the REFERENCE constraint
"FK_OrderItem_Order". The conflict occurred in database "Test", table
"dbo.OrderItem", c...
Tables:
USE [Test]
GO
/****** Object: Table [dbo].[Order] Script Date: 6/9/2016 2:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Order](
[Id] [int] IDENTITY(1,1) NOT NULL,
[OrderNum] [varchar](20) NOT NULL,
[Description] [varchar](100) NULL,
CONSTRAINT [PK_Order] 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
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[OrderItem] Script Date: 6/9/2016 2:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[OrderItem](
[Id] [int] IDENTITY(1,1) NOT NULL,
[OrderId] [int] NOT NULL,
[OrderItemName] [varchar](100) NOT NULL,
[Qty] [int] NOT NULL,
CONSTRAINT [PK_OrderItem] 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
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[OrderItem] WITH CHECK ADD CONSTRAINT [FK_OrderItem_Order] FOREIGN KEY([OrderId])
REFERENCES [dbo].[Order] ([Id])
GO
ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_OrderItem_Order]
GO
Here is my LINQ statement
List<Order> olist = (from a in Orders where a.Id == 2 select a).ToList();
List<int> olistidlist = olist.Select (o => o.Id).ToList();
List<OrderItem> oilist = (from a in OrderItems where olistidlist.Contains(a.Id) select a).ToList();
//see results before
olist.Dump();
OrderItems.DeleteAllOnSubmit(oilist);
Orders.DeleteAllOnSubmit(olist);
//save changes
SubmitChanges();
//see results after
olist.Dump();
You are deleting OrderItems of which the OrderItem.Id is equal to values in olistidlist (only 2, presently). Of course, this must be OrderItem.OrderId.
By the way, an easier way to delete parent and child items generally is:
foreach (var order in Orders.Where(...))
{
OrderItems.DeleteAllOnSubmit(order.OrderItems);
Orders.DeleteOnSubmit(order);
}
So you don't have to move around with Id values.

Trigger not triggering

I've got two tables as per diagram below
here is sql script for USERS TABLES
USE [NewUser]
GO
/****** Object: Table [dbo].[USERS] Script Date: 15/12/2014 18:26:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[USERS](
[FirstName] [varchar](50) NULL,
[SureName] [varchar](50) NULL,
[DOB] [date] NULL,
[USID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_USERS] PRIMARY KEY CLUSTERED
(
[USID] 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
And for ADDRESSES TABLE
USE [NewUser]
GO
/****** Object: Table [dbo].[ADDRESSES] Script Date: 15/12/2014 18:26:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ADDRESSES](
[AID] [int] IDENTITY(1,1) NOT NULL,
[USID] [numeric](18, 0) NULL,
[AddressLine1] [varchar](50) NULL,
[AddressLine2] [varchar](50) NULL,
[PostCode] [varchar](50) NULL,
CONSTRAINT [PK_ADDRESSES] PRIMARY KEY CLUSTERED
(
[AID] 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
ALTER TABLE [dbo].[ADDRESSES] WITH CHECK ADD CONSTRAINT [FK_ADDRESSES_USERS]
FOREIGN KEY([USID])
REFERENCES [dbo].[USERS] ([USID])
ON UPDATE CASCADE
ON DELETE SET NULL
GO
ALTER TABLE [dbo].[ADDRESSES] CHECK CONSTRAINT [FK_ADDRESSES_USERS]
GO
After that I have created a TRIGGER using
USE [NewUser]
GO
/****** Object: Trigger [dbo].[autoupdate] Script Date: 15/12/2014 18:33:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[autoupdate]
ON [dbo].[USERS]
AFTER INSERT, DELETE, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TEMPID INT
SET #TEMPID = (SELECT USID FROM INSERTED)
UPDATE ADDRESSES
SET USID = #TEMPID
END
The purpose of the TRIGGER is to insert UID automatically on the second table as soon as a new row is added or updated in first table.
But its not doing what I was expecting it to do.
Screenshots
USERS TABLE
ADDRESSES TABLE
USID from table USERS and AID from table ADDRESSES both has "Is Identity Set to YESS"
I'm assuming this is SQL Server, not MySql - please remove the conflicting RDBMS tag.
With triggers, you'll need to handle set data - the INSERTED and DELETED pseudocolumns are tables, not single rows.
Also, assuming that you aren't going to be updating the PK [USID] on Users, you won't need to handle an UPDATE in the trigger, just INSERT and DELETE, and it looks like you've already decided to handle deletes on user with ON DELETE SET NULL, which will set the USID foreign key to NULL in Addresses.
So this leaves INSERT - I'm guessing here you only want to insert an empty address for new users?:
ALTER TRIGGER [dbo].[autoupdate]
ON [dbo].[USERS]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO ADDRESSES(USID)
SELECT USID FROM INSERTED i
WHERE NOT EXISTS (SELECT 1 FROM ADDRESSES a WHERE a.USID = i.USID)
AND i.USID IS NOT NULL;
END
In order for your trigger to do anything the way you've designed it, you need to have records already in the Addresses table. Once a record exists, it's USID will be updated when a record is updated or inserted in the Users table.

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

Identity Problems During Database Creation

Using SQL Server Management Studio, my issue stems from a database creation script. The script is written to create a database, many of whose tables have an identity column:
CREATE TABLE Workshop
(
WorkshopID int IDENTITY,
WorkshopName varchar(40) NOT NULL,
Description varchar(800),
CONSTRAINT PK_Workshop PRIMARY KEY (WorkshopID)
);
My issue is that even with the script plainly creating a column as an identity column, after the script runs none of the columns that should be identity columns actually have that column set to be identity.
To clarify: Running the above code will create that table as specified except WorkshopID will not be an identity column.
What needs to change so that the script will work as written?
FYI, if you generate script for this using SQL Management Studio's designer, this is the resulting script:
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Table_1
(
WorkshopID int NOT NULL IDENTITY (1, 1),
WorkshopName varchar(40) NOT NULL,
Description varchar(800) NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Table_1 ADD CONSTRAINT
PK_Table_1 PRIMARY KEY CLUSTERED
(
WorkshopID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE dbo.Table_1 SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
If you create the table and then script it using the Create To... menu option you get a completely different script:
USE [MyDatabase]
GO
/****** Object: Table [dbo].[Workshop] Script Date: 11/27/2012 14:05:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Workshop](
[WorkshopID] [int] IDENTITY(1,1) NOT NULL,
[WorkshopName] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Description] [varchar](800) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_Workshop] PRIMARY KEY CLUSTERED
(
[WorkshopID] 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

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

Resources