'Incorrect SET Options' Error When Building Database Project - sql-server

We are using Visual Studio and a database project to generate our database.
I just made a number of database changes (including adding a new table named Correspondence) imported those changes into the database project, and attempted to deploy (rebuild) the database.
When I do, I get the following error:
Creating [dbo].[Correspondence]...
Msg 1934, Level 16, State 1, Server (Server Name), Line 1
CREATE TABLE failed because the following SET options have incorrect settings
: 'ANSI_WARNINGS, ANSI_PADDING'. Verify that SET options are correct for use
with indexed views and/or indexes on computed columns and/or filtered indexes
and/or query notifications and/or XML data type methods and/or spatial index
operations.
Can anyone explain this error to me, and help me resolve it? Here's the script the database project uses to create this table.
PRINT N'Creating [dbo].[Correspondence]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
CREATE TABLE [dbo].[Correspondence] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[WorkbookId] INT NOT NULL,
[ProviderId] UNIQUEIDENTIFIER NOT NULL,
[MessageThreadId] INT NOT NULL,
[MessageThreadType] AS ((1)) PERSISTED NOT NULL
);
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
PRINT N'Creating PK_Correspondence...';
GO
ALTER TABLE [dbo].[Correspondence]
ADD CONSTRAINT [PK_Correspondence] PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF,
IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
GO

According to BOL:
Indexed views and indexes on computed columns store results in the
database for later reference. The stored results are valid only if all
connections referring to the indexed view or indexed computed column
can generate the same result set as the connection that created the
index.
In order to create a table with a persisted, computed column, the following connection settings must be enabled:
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET NUMERIC_ROUNDABORT ON
SET QUOTED_IDENTIFIER ON
These values are set on the database level and can be viewed using:
SELECT
is_ansi_nulls_on,
is_ansi_padding_on,
is_ansi_warnings_on,
is_arithabort_on,
is_concat_null_yields_null_on,
is_numeric_roundabort_on,
is_quoted_identifier_on
FROM sys.databases
However, the SET options can also be set by the client application connecting to SQL Server.
A perfect example is SQL Server Management Studio which has the default values for SET ANSI_NULLS and SET QUOTED_IDENTIFIER both to ON. This is one of the reasons why I could not initially duplicate the error you posted.
Anyway, to duplicate the error, try this (this will override the SSMS default settings):
SET ANSI_NULLS ON
SET ANSI_PADDING OFF
SET ANSI_WARNINGS OFF
SET ARITHABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET NUMERIC_ROUNDABORT OFF
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE T1 (
ID INT NOT NULL,
TypeVal AS ((1)) PERSISTED NOT NULL
)
You can fix the test case above by using:
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
I would recommend tweaking these two settings in your script before the creation of the table and related indexes.

I found the solution for this problem:
Go to the Server Properties.
Select the Connections tab.
Check if the ansi_padding option is unchecked.

In my case I was trying to create a table from one database to another on MS SQL Server 2012. Right-clicking on a table and selecting Script Table as > DROP And CREATE To > New Query Editor Window, following script was created:
USE [SAMPLECOMPANY]
GO
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[FullName] [varchar](50) NOT NULL,
[HireDate] [datetime] NULL
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[EmployeeId] 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].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
However when executing above script it was returning the error:
SELECT failed because the following SET options have incorrect
settings: 'ANSI_PADDING'. Verify that SET options are correct for use
with indexed views and/or indexes on computed columns and/or filtered
indexes and/or query notifications and/or XML data type methods and/or
spatial index operations.
The Solution I've found: Enabling the settings on the Top of the script like this:
USE [SAMPLECOMPANY]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[FullName] [varchar](50) NOT NULL,
[HireDate] [datetime] NULL
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[EmployeeId] 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].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
SET ANSI_PADDING OFF
GO
Hope this help.

For me, just setting the compatibility level to higher level works fine. To see C.Level :
select compatibility_level from sys.databases where name = [your_database]

In my case, I found that a computed column had been added to the "included columns" of an index. Later, when an item in that table was updated, the merge statement failed with that message. The merge was in a trigger, so this was hard to track down! Removing the computed column from the index fixed it.

I had the same issue with the filtered index and my inserts and updates were failing. All I did was to change the stored procedure that had the insert and update statement to:
create procedure abc
()
AS
BEGIN
SET NOCOUNT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_WARNINGS ON
SET ANSI_PADDING ON
end

Related

Generating script from existing table having too much detail

When i use SQL Server Management Studio GUI to generate script of a table of an existing database, it produces the following:
USE [BikeStores]
GO
/****** Object: Table [production].[brands2] Script Date: 9/20/2019 3:44:27 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [production].[brands2](
[brand_id] [int] IDENTITY(1,1) NOT NULL,
[brand_name] [varchar](255) NOT NULL,
PRIMARY KEY CLUSTERED
(
[brand_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
But i want the simple table script as follows
CREATE TABLE production.brands2 (
brand_id INT IDENTITY (1, 1) PRIMARY KEY,
brand_name VARCHAR (255) NOT NULL
);
You will not be able to create the desired output in SSMS. However, you can do some slight changes in SSMS of what to output when you script your table. For example you can choose not to
Script Indexes, Triggers and Foreign keys. Etc..
Go to Tools -> Options -> Sql Server Object Explorer -> Scripting

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.

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

Change all SQL Server Columns From BigInt to Int

I have inherited a database I need to work with. All the numeric fields have been set to bigint (without reason they are all sub 5000).
How can I programmticaly change all the columns of big int to int? Is this possible will it cause issue with any existing constraints etc?
I only want to change tables and only in the specific database I am working on.
I am using SQL Server 2008 R2
I need to do this for hundreds of fields I am looking for something that I can run once and it will do all the updates for all table fields. I want to keep any existing constraints, null status and default values.
So basically a database wide change of bigint to int without changing anything apart from the field type.
Thanks
Well, I had come across this kind of problem. I had to change int to bigint. This is harder, but possible. It is very easy to change datatype using the following statement:
Alter table myTable alter column targetcolumn int not null
However if your columns are involved in constraint relationship then you have to drop your constraints then alter and then recreate your constraints.
Alter table myTable drop constraint [fkconstraintname]
Alter table myTable alter column targetcolumn int not null
Alter table othertable alter column targetcolumn int not null
Alter table myTable add constraint [fkconstraintname] foreign key (targetcolumn) references othertable(targetcolumn)
EDIT
If you have a lot of constraints then changing it is a real pain in the butt. If there are a lot of tables with constraints and no extreme urge at changing don't do it.
EDIT
Then you can do the following. Connect to Sql Server via Management Studio, right click on the necessary database => Tasks => Generate scripts.
Next => Next
At that point press advanced. There will be a popup. Set Type of data to script to schema and data. Choose whatever output is comfortable for you (file, query window)? Press ok and proceed. It will produce you a complete DDL and DML, like this:
USE [master]
GO
/****** Object: Database [Zafarga] Script Date: 02/02/2012 19:31:55 ******/
CREATE DATABASE [Zafarga] ON PRIMARY
GO
ALTER DATABASE [Zafarga] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [Zafarga].[dbo].[sp_fulltext_database] #action = 'enable'
end
GO
ALTER DATABASE [Zafarga] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [Zafarga] SET ANSI_NULLS OFF
GO
ALTER DATABASE [Zafarga] SET ANSI_PADDING OFF
GO
ALTER DATABASE [Zafarga] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [Zafarga] SET ARITHABORT OFF
GO
ALTER DATABASE [Zafarga] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [Zafarga] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [Zafarga] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [Zafarga] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [Zafarga] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [Zafarga] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [Zafarga] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [Zafarga] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [Zafarga] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [Zafarga] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [Zafarga] SET ENABLE_BROKER
GO
ALTER DATABASE [Zafarga] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [Zafarga] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [Zafarga] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [Zafarga] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [Zafarga] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [Zafarga] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [Zafarga] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [Zafarga] SET READ_WRITE
GO
ALTER DATABASE [Zafarga] SET RECOVERY FULL
GO
ALTER DATABASE [Zafarga] SET MULTI_USER
GO
ALTER DATABASE [Zafarga] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [Zafarga] SET DB_CHAINING OFF
GO
EXEC sys.sp_db_vardecimal_storage_format N'Zafarga', N'ON'
GO
USE [Zafarga]
GO
/****** Object: Table [dbo].[Category] Script Date: 02/02/2012 19:31:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Category](
[CategoryId] [bigint] IDENTITY(1,1) NOT NULL,
[CategoryName] [nvarchar](max) NULL,
PRIMARY KEY CLUSTERED
(
[CategoryId] 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
/****** Object: Table [dbo].[Product] Script Date: 02/02/2012 19:31:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
[ProductId] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Price] [decimal](18, 2) NOT NULL,
[CategoryId] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED
(
[ProductId] 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
/****** Object: ForeignKey [Category_Products] Script Date: 02/02/2012 19:31:56 ******/
ALTER TABLE [dbo].[Product] WITH CHECK ADD CONSTRAINT [Category_Products] FOREIGN KEY([CategoryId])
REFERENCES [dbo].[Category] ([CategoryId])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [Category_Products]
GO
Change all your datatypes appropriately, then run.
As you said all your data is below 5000 rows. So there is no need to modify insert statements.
Be ready it will take a long time.
Hope this was useful.
EDIT
This will generate you a new database, so be ready to rename your original or newly created db.
I think #Oybek says this in one of his addenda, I’m giving him +1, but just to be certain I’ll outline how I’d do it. (This assumes you have a lot of constraints across lots of bigint tables; if not, doing them one by one might be simpler.)
Use SSMS to script the entire database. (That’s right-click the database in the Object Explorer pane, Script Database As, CREATE TO, and I’d to it to a new query window and save it as a file.
Search and replace all bigints with ints. (Do this slowly, make sure you change only what needs to be changed.)
Modify the script to create a new database (different name, different files)
Run and create the database.
The hard part: copy the data from the tables of the old database to the new database.
If, as you say, all the bigints will fit into ints, you shouldn’t have any problems; the hard part is figuring out how to actually do it all. There’s got to be some way to do this via the SSMS Import or Export wizard, but I’m not all that familiar with those tools. Barring that, creating a series of INSERT… SELECT… statements performed in order of parent through child tables, with SET IDENTITY INSERTs as necessary, should do the trick.
I'd do it like this:
Rename YourTable to YourTable_OLD
Right click table -> Script table as Create -> to new query window
adjust the script to use int and rename table to the original
Create the new table and call it YourTable to replace the old
insert YourTable select * from YourTable_OLD
Drop YourTable_OLD (when you're sure everything went ok)
I guess that would be quickest. If you do it column by column it needs to convert it column by column. This involves a lot of IO that could become a problem, depending on the size of your table.
Regards GJ
id addition to the answers, dont forget to check it all the values on the columns are on the integer range (between -2,147,483,648 and 2,147,483,647).
To automate #Oleg Dok's answer you could run his solution inside a script that loops through all tables and all columns on your DB
Regarding to Martin Smith - its much simplier, than I thought:
ALTER TABLE YourTable MODIFY COLUMN OldColumn INT [NOT] NULL
thats all
Old version of answer:
If new column should not be nullable:
ALTER TABLE YourTable ADD NewFIeld INT NOT NULL DEFAULT (CAST(OldField AS INT))
GO
ALTER TABLE YourTable DROP COLUMN OldField
GO
exec sp_rename 'YourTable.NewField', 'OldField', 'COLUMN'
OR which is mostly the same, relaxed for nullable column - does not holds locks on system tables while performing the update
ALTER TABLE YourTable ADD NewFIeld INT NULL
GO
UPDATE YourTable SET NewField=OldField
GO
ALTER TABLE YourTable DROP COLUMN OldField
GO
exec sp_rename 'YourTable.NewField', 'OldField', 'COLUMN'

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