I can't drop an index because some tables used it for foreign key
Msg 3723, Level 16, State 6, Line 1 An explicit DROP INDEX is not
allowed on index 'tbl1.ix_cox'. It is being used for FOREIGN KEY
constraint enforcement.
I tried to disable the index first before dropping
ALTER INDEX ix_cox On tbl1
DISABLE
Go
But still don't able to drop it.
Do I really need to remove the foreign key on those tables that used that index? Because it is about 30 tables.
You'll get the same exception if the index was created defining a PRIMARY KEY or UNIQUE constraint (https://learn.microsoft.com/en-us/sql/t-sql/statements/drop-index-transact-sql?view=sql-server-2017).
In that case the simple solution is to use the ALTER-TABLE-command instead:
ALTER TABLE tbl1 DROP CONSTRAINT ix_cox
I am afraid this is the only option you have. you have to drop all foreign key constraints referencing to table and also you cannot recreate the foreign key constraints until you specify another unique index on the table from where you removed index.
Good day,
Here is a full example:
Let's create the tables and insert some sample data first
use tempdb
GO
-- NOTE!
-- This sample code presents a POOR CODING where the user
-- does not explicitly named the objects
-- or explicitly create CLUSTERED INDEX
DROP TABLE IF EXISTS dbo.Users_tbl;
DROP TABLE IF EXISTS dbo.Categories_tbl;
GO
CREATE TABLE dbo.Categories_tbl(
CategoryID INT IDENTITY(1,1) PRIMARY KEY
, CategoryName NVARCHAR(100)
)
GO
-- find the CLUSTERED INDEX created automatically for us
SELECT * FROM sys.indexes
WHERE object_id = OBJECT_ID('Categories_tbl')
GO
-- you can notice that by default the PRIMARY KEY become CLUSTERED INDEX
-- If we did not configure a different CLUSTERED INDEX
-- In my case the automatic name was: PK__Categori__19093A2BAE0EA4C3
-- Let's create the secondary table
CREATE TABLE dbo.Users_tbl(
UserID INT IDENTITY(1,1) PRIMARY KEY
, UserName NVARCHAR(100)
, CategoryID INT
, FOREIGN KEY (CategoryID) REFERENCES Categories_tbl(CategoryID)
)
GO
-- Insert sample data
INSERT Categories_tbl (CategoryName) VALUES ('a'),('b')
GO
INSERT Users_tbl(UserName,CategoryID)
VALUES ('a',1),('b',1)
GO
SELECT * FROM Categories_tbl
SELECT * FROM Users_tbl
GO
REMOVE CLUSTERED INDEX from PRIMARY KEY
If we will try to DROP INDEX of the PK then we will get this error:
An explicit DROP INDEX is not allowed on index... It is being used for PRIMARY KEY constraint enforcement.
The solution is to drop the FK, Drop the PK, Create new PK with NONCLUSTERED index instead of CLUSTERED, and create the FK
/************************************************ */
/********* REMOVE CLUSTERED INDEX from PRIMARY KEY */
/************************************************ */
------------------------------------------------------
-- Step 1: DROP the CONSTRAINTs
------------------------------------------------------
---- Get FOREIGN KEY name
SELECT DISTINCT OBJECT_NAME(f.constraint_object_id)
FROM sys.foreign_key_columns f
LEFT JOIN sys.indexes p ON p.object_id = f.referenced_object_id
WHERE p.object_id = OBJECT_ID('Categories_tbl')
GO
-- DROP FOREIGN KEY
ALTER TABLE dbo.Users_tbl
DROP CONSTRAINT FK__Users_tbl__Categ__59063A47 -- Use the name we found above
GO
---- Get PRIMARY KEY name
SELECT name FROM sys.indexes
WHERE object_id = OBJECT_ID('Categories_tbl')
GO
-- DROP PRIMARY KEY
ALTER TABLE dbo.Categories_tbl
DROP CONSTRAINT PK__Categori__19093A2B9F118674 -- Use the name we found above
GO
------------------------------------------------------
-- Step 2: CREATE new CONSTRAINTs
------------------------------------------------------
-- And now we can create new PRIMARY KEY NONCLUSTERED
-- Since we use PRIMARY KEY We need to have index,
-- but we do not have to use CLUSTERED INDEX
-- we can have NONCLUSTERED INDEX
ALTER TABLE dbo.Categories_tbl
ADD CONSTRAINT PK_CategoryID PRIMARY KEY NONCLUSTERED (CategoryID);
GO
-- Finaly we can create the
ALTER TABLE dbo.Users_tbl
ADD CONSTRAINT FK_Categories_tbl
FOREIGN KEY (CategoryID)
REFERENCES dbo.Categories_tbl(CategoryID)
GO
You can disable the FK constraint for temporary being -> drop the index -> re-enable the constraint back like
ALTER TABLE your_fk_table NOCHECK CONSTRAINT constraint_name
drop index ids_name
ALTER TABLE your_fk_table CHECK CONSTRAINT constraint_name
Well, if you have an FK on 30 tables like EzLo, it would sure be nice to have some automation. The script in the last two columns of this view will drop and re-add your FK's:
CREATE VIEW vwFK
AS
select *, addFK = 'ALTER TABLE '+FKtable+' WITH ' + case when is_not_trusted = 1 then 'NO' else '' end + 'CHECK'
+ ' ADD CONSTRAINT [FK_'+FKtbl+'_'+PKtbl+'] FOREIGN KEY ('+FKcol+') '
+ ' REFERENCES '+PKtable+' ('+PKcol+')'+' ON UPDATE '+onUpdate+' ON DELETE '+onDelete
+ case when is_not_for_replication = 1 then ' NOT FOR REPLICATION' else '' end + ';'
+ case when is_disabled = 1 then ' ALTER TABLE '+FKtable+' NOCHECK CONSTRAINT [FK_'+FKtbl+'_'+PKtbl+'];' else '' end
,dropFK = 'ALTER TABLE '+FKtable+' DROP ['+FK+'];'
from (
select
PKtable = object_schema_name(f.referenced_object_id)+'.'+object_name(f.referenced_object_id)
,PKtbl = object_name(f.referenced_object_id)
,PKcol = pc.name
,FKtable = object_schema_name(f.parent_object_id)+'.'+object_name(f.parent_object_id)
,FKtbl = object_name(f.parent_object_id)
,colseq = fk.constraint_column_id
,FKcol = fc.name
,FK = object_name(f.object_id)
,onUpdate = replace(f.update_referential_action_desc collate SQL_Latin1_General_CP1_CI_AS, '_', ' ')
,onDelete = replace(f.delete_referential_action_desc collate SQL_Latin1_General_CP1_CI_AS, '_', ' ')
,f.is_disabled
,f.is_not_trusted
,f.is_not_for_replication
from sys.foreign_key_columns as fk
join sys.foreign_keys f on fk.constraint_object_id = f.object_id
join sys.columns as fc on f.parent_object_id = fc.object_id and fk.parent_column_id = fc.column_id
join sys.columns as pc on f.referenced_object_id = pc.object_id and fk.referenced_column_id = pc.column_id
) t
No guarantees, but this has saved me a lot of work over the years. Just remember to save the addFK statements before running your dropFK's!
Related
I am creating Clustered Index on a table and Dropping if it already exists.
I am using this Query.
DROP INDEX IF EXISTS CLX_Enrolment_StudentID_BatchID
ON Enrollment
CREATE INDEX CLX_Enrolment_StudentID_BatchID
ON Enrollment(Studentid, BatchId ASC);
Now,I want to know which Cluster is getting created here:-
Is this a Clustered or Non-Clustered?
CREATE INDEX CLX_Enrolment_StudentID_BatchID
ON Enrollment(Studentid, BatchId ASC);
Because on using:-
DROP clustered INDEX IF EXISTS CLX_Enrolment_StudentID_BatchID
ON Enrollment
I am getting this error:-
Incorrect syntax near the keyword 'clustered'.
And,If I use:-
DROP INDEX IF EXISTS CLX_Enrolment_StudentID_BatchID
ON Enrollment
go
CREATE clustered INDEX CLX_Enrolment_StudentID_BatchID
ON Enrollment(Studentid, BatchId ASC);
I am getting this error:-
Cannot create more than one clustered index on table 'Enrollment'. Drop the existing clustered index 'PK__enrollme__DE799CE1E4649295' before creating another.
Now,I want to know in my Second Query which Index is getting created. And, If none of both is getting created then how to remove Clustered Index if it exists and create a new one.
You can try to use IF EXISTS syntax to check sys.indexes table whether contains the index.
IF EXISTS(
SELECT *
FROM sys.indexes
WHERE name='CLX_Enrolment_StudentID_BatchID' AND OBJECT_ID = OBJECT_ID('Enrollment')
)
BEGIN
DROP INDEX CLX_Enrolment_StudentID_BatchID ON [dbo].[Enrollment]
END
GO
CREATE clustered INDEX CLX_Enrolment_StudentID_BatchID
ON Enrollment(Studentid, BatchId ASC);
But I think there is an index PK__enrollme__DE799CE1E4649295 on your table from your error message.
Modify
If you want to DROP PK or Clustered index automatically, you can try to use dynamic sql to create the script and use sp_executesql to exec that.
DECLARE #sql NVARCHAR(500),
#TableName VARCHAR(50) = 'Enrollment',
#Para NVARCHAR(500)='#TableName VARCHAR(50)'
SELECT #sql = CONCAT('ALTER TABLE ',#TableName,' DROP CONSTRAINT ',name)
FROM sys.indexes
WHERE OBJECT_ID = OBJECT_ID(#TableName) AND type_desc = 'CLUSTERED' AND is_primary_key = 1
EXEC sp_executesql #sql,#Para,#TableName
SELECT #sql = CONCAT('DROP INDEX ',name,' ON dbo.',#TableName)
FROM sys.indexes
WHERE OBJECT_ID = OBJECT_ID(#TableName) AND type_desc = 'CLUSTERED'
EXEC sp_executesql #sql,#Para,#TableName
if your table already contains PK you need to use ALTER TABLE .... DROP CONSTRAINT instead of drop index.
We have a 5GB table (nearly 500 million rows) and we want to remove the identity property on one of the column, but when we try to do this through SSMS - it times out.
Can this be done through T-SQL?
You cannot remove an IDENTITY specification once set.
To remove the entire column:
ALTER TABLE yourTable
DROP COLUMN yourCOlumn;
Information about ALTER TABLE here
If you need to keep the data, but remove the IDENTITY column, you will need to:
Create a new column
Transfer the data from the existing IDENTITY column to the new column
Drop the existing IDENTITY column.
Rename the new column to the original column name
If you want to do this without adding and populating a new column, without reordering the columns, and with almost no downtime because no data is changing on the table, let's do some magic with partitioning functionality (but since no partitions are used you don't need Enterprise edition):
Remove all foreign keys that point to this table
Script the table to be created; rename everything e.g. 'MyTable2', 'MyIndex2', etc.
Remove the IDENTITY specification.
You should now have two "identical"-ish tables, one full, the other empty with no IDENTITY.
Run ALTER TABLE [Original] SWITCH TO [Original2]
Now your original table will be empty and the new one will have the data. You have switched the metadata for the two tables (instant).
Drop the original (now-empty table), exec sys.sp_rename to rename the various schema objects back to the original names, and then you can recreate your foreign keys.
For example, given:
CREATE TABLE Original
(
Id INT IDENTITY PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value ON Original (Value);
INSERT INTO Original
SELECT 'abcd'
UNION ALL
SELECT 'defg';
You can do the following:
--create new table with no IDENTITY
CREATE TABLE Original2
(
Id INT PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value2 ON Original2 (Value);
--data before switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;
ALTER TABLE Original SWITCH TO Original2;
--data after switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;
--clean up
IF NOT EXISTS (SELECT * FROM Original) DROP TABLE Original;
EXEC sys.sp_rename 'Original2.IX_Original_Value2', 'IX_Original_Value', 'INDEX';
EXEC sys.sp_rename 'Original2', 'Original', 'OBJECT';
UPDATE Original
SET Id = Id + 1;
SELECT *
FROM Original;
For the record, as this has become increasingly popular, I have wanted to track down the original source (I didn't think of it myself), but of course I've long forgotten where I found the original idea. It may have been here; this was the only one I could find predating this answer (time flies, boys and girls): https://social.technet.microsoft.com/wiki/contents/articles/17738.sql-server-quick-way-to-remove-the-identity-property.aspx
This gets messy with foreign and primary key constraints, so here's some scripts to help you on your way:
First, create a duplicate column with a temporary name:
alter table yourTable add tempId int NOT NULL default -1;
update yourTable set tempId = id;
Next, get the name of your primary key constraint:
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'yourTable';
Now try drop the primary key constraint for your column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
If you have foreign keys, it will fail, so if so drop the foreign key constraints. KEEP TRACK OF WHICH TABLES YOU RUN THIS FOR SO YOU CAN ADD THE CONSTRAINTS BACK IN LATER!!!
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'otherTable';
alter table otherTable drop constraint fk_otherTable_yourTable;
commit;
..
Once all of your foreign key constraints have been removed, you'll be able to remove the PK constraint, drop that column, rename your temp column, and add the PK constraint to that column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
alter table yourTable drop column id;
EXEC sp_rename 'yourTable.tempId', 'id', 'COLUMN';
ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id)
commit;
Finally, add the FK constraints back in:
alter table otherTable add constraint fk_otherTable_yourTable foreign key (yourTable_id) references yourTable(id);
..
El Fin!
I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.
Make a new column
alter table users add newusernum int;
Copy values over
update users set newusernum=usernum;
Drop the old column
alter table users drop column usernum;
Rename the new column to the old column name
EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';
Following script removes Identity field for a column named 'Id'
Hope it helps.
BEGIN TRAN
BEGIN TRY
EXEC sp_rename '[SomeTable].[Id]', 'OldId';
ALTER TABLE [SomeTable] ADD Id int NULL
EXEC ('UPDATE [SomeTable] SET Id = OldId')
ALTER TABLE [SomeTable] NOCHECK CONSTRAINT ALL
ALTER TABLE [SomeTable] DROP CONSTRAINT [PK_constraintName];
ALTER TABLE [SomeTable] DROP COLUMN OldId
ALTER TABLE [SomeTable] ALTER COLUMN [Id] INTEGER NOT NULL
ALTER TABLE [SomeTable] ADD CONSTRAINT PK_JobInfo PRIMARY KEY (Id)
ALTER TABLE [SomeTable] CHECK CONSTRAINT ALL
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
SELECT ERROR_MESSAGE ()
END CATCH
Bellow code working as fine, when we don't know identity column name.
Need to copy data into new temp table like Invoice_DELETED.
and next time we using:
insert into Invoice_DELETED select * from Invoice where ...
SELECT t1.*
INTO Invoice_DELETED
FROM Invoice t1
LEFT JOIN Invoice ON 1 = 0
--WHERE t1.InvoiceID = #InvoiceID
For more explanation see:
https://dba.stackexchange.com/a/138345/101038
ALTER TABLE tablename add newcolumn int
update tablename set newcolumn=existingcolumnname
ALTER TABLE tablename DROP COLUMN existingcolumnname;
EXEC sp_RENAME 'tablename.oldcolumn' , 'newcolumnname', 'COLUMN'
However above code works only if no primary-foreign key relation
In SQL Server you can turn on and off identity insert like this:
SET IDENTITY_INSERT table_name ON
-- run your queries here
SET IDENTITY_INSERT table_name OFF
Just for someone who have the same problem I did.
If you just want to make some insert just once you can do something like this.
Lets suppose you have a table with two columns
ID Identity (1,1) | Name Varchar
and want to insert a row with the ID = 4. So you Reseed it to 3 so the next one is 4
DBCC CHECKIDENT([YourTable], RESEED, 3)
Make the Insert
INSERT INTO [YourTable]
( Name )
VALUES ( 'Client' )
And get your seed back to the highest ID, lets suppose is 15
DBCC CHECKIDENT([YourTable], RESEED, 15)
Done!
I had the same requirement, and you could try this way, which I personally recommend you, please manually design your table and generate the script, and what I did below was renaming the old table and also its constraint for backup.
/* 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
ALTER TABLE dbo.SI_Provider_Profile
DROP CONSTRAINT DF_SI_Provider_Profile_SIdtDateTimeStamp
GO
ALTER TABLE dbo.SI_Provider_Profile
DROP CONSTRAINT DF_SI_Provider_Profile_SIbHotelPreLoaded
GO
CREATE TABLE dbo.Tmp_SI_Provider_Profile
(
SI_lProvider_Profile_ID int NOT NULL,
SI_lSerko_Integrator_Token_ID int NOT NULL,
SI_sSerko_Integrator_Provider varchar(50) NOT NULL,
SI_sSerko_Integrator_Profile varchar(50) NOT NULL,
SI_dtDate_Time_Stamp datetime NOT NULL,
SI_lProvider_ID int NULL,
SI_sDisplay_Name varchar(10) NULL,
SI_lPurchased_From int NULL,
SI_sProvider_UniqueID varchar(255) NULL,
SI_bHotel_Pre_Loaded bit NOT NULL,
SI_sSiteName varchar(255) NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile SET (LOCK_ESCALATION = TABLE)
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile ADD CONSTRAINT
DF_SI_Provider_Profile_SIdtDateTimeStamp DEFAULT (getdate()) FOR SI_dtDate_Time_Stamp
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile ADD CONSTRAINT
DF_SI_Provider_Profile_SIbHotelPreLoaded DEFAULT ((0)) FOR SI_bHotel_Pre_Loaded
GO
IF EXISTS(SELECT * FROM dbo.SI_Provider_Profile)
EXEC('INSERT INTO dbo.Tmp_SI_Provider_Profile (SI_lProvider_Profile_ID, SI_lSerko_Integrator_Token_ID, SI_sSerko_Integrator_Provider, SI_sSerko_Integrator_Profile, SI_dtDate_Time_Stamp, SI_lProvider_ID, SI_sDisplay_Name, SI_lPurchased_From, SI_sProvider_UniqueID, SI_bHotel_Pre_Loaded, SI_sSiteName)
SELECT SI_lProvider_Profile_ID, SI_lSerko_Integrator_Token_ID, SI_sSerko_Integrator_Provider, SI_sSerko_Integrator_Profile, SI_dtDate_Time_Stamp, SI_lProvider_ID, SI_sDisplay_Name, SI_lPurchased_From, SI_sProvider_UniqueID, SI_bHotel_Pre_Loaded, SI_sSiteName FROM dbo.SI_Provider_Profile WITH (HOLDLOCK TABLOCKX)')
GO
-- Rename the primary key constraint or unique key In SQL Server constraints such as primary keys or foreign keys are objects in their own right, even though they are dependent upon the "containing" table.
EXEC sp_rename 'dbo.SI_Provider_Profile.PK_SI_Provider_Profile', 'PK_SI_Provider_Profile_Old';
GO
-- backup old table in case of
EXECUTE sp_rename N'dbo.SI_Provider_Profile', N'SI_Provider_Profile_Old', 'OBJECT'
GO
EXECUTE sp_rename N'dbo.Tmp_SI_Provider_Profile', N'SI_Provider_Profile', 'OBJECT'
GO
ALTER TABLE dbo.SI_Provider_Profile ADD CONSTRAINT
PK_SI_Provider_Profile PRIMARY KEY NONCLUSTERED
(
SI_lProvider_Profile_ID
) WITH( PAD_INDEX = OFF, FILLFACTOR = 90, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT TRANSACTION
ALTER TABLE TABLE_NAME MODIFY (COLUMN_NAME DROP IDENTITY);
I am trying to add a clustered index to an existing table in SQL Server 2008, and it needs to be an automated script, because this table exists on several databases across several servers.
In order to add a clustered index I need to remove the PK constraint on the table, and then re-add it as unclustered. The problem is the name of the PK constraint is auto-generated, and there is a guid appended to the end, so it's like "PK_[Table]_D9F9203400."
The name is different across all databases, and I'm not sure how to write an automated script that drops a PK constraint on a table in which I don't know the name of the constraint. Any help is appreciated!
UPDATE:
Answer below is what I used. Full script:
Declare #Val varchar(100)
Declare #Cmd varchar(1000)
Set #Val = (
select name
from sysobjects
where xtype = 'PK'
and parent_obj = (object_id('[Schema].[Table]'))
)
Set #Cmd = 'ALTER TABLE [Table] DROP CONSTRAINT ' + #Val
Exec (#Cmd)
GO
ALTER TABLE [Table] ADD CONSTRAINT PK_Table
PRIMARY KEY NONCLUSTERED (TableId)
GO
CREATE UNIQUE CLUSTERED INDEX IX_Table_Column
ON Table (Column)
GO
You can look up the name of the constraint and write a bit of dynamic SQL to handle the drop.
SELECT name
FROM sys.key_constraints
WHERE parent_object_id = object_id('YourSchemaName.YourTableName')
AND type = 'PK';
We have a 5GB table (nearly 500 million rows) and we want to remove the identity property on one of the column, but when we try to do this through SSMS - it times out.
Can this be done through T-SQL?
You cannot remove an IDENTITY specification once set.
To remove the entire column:
ALTER TABLE yourTable
DROP COLUMN yourCOlumn;
Information about ALTER TABLE here
If you need to keep the data, but remove the IDENTITY column, you will need to:
Create a new column
Transfer the data from the existing IDENTITY column to the new column
Drop the existing IDENTITY column.
Rename the new column to the original column name
If you want to do this without adding and populating a new column, without reordering the columns, and with almost no downtime because no data is changing on the table, let's do some magic with partitioning functionality (but since no partitions are used you don't need Enterprise edition):
Remove all foreign keys that point to this table
Script the table to be created; rename everything e.g. 'MyTable2', 'MyIndex2', etc.
Remove the IDENTITY specification.
You should now have two "identical"-ish tables, one full, the other empty with no IDENTITY.
Run ALTER TABLE [Original] SWITCH TO [Original2]
Now your original table will be empty and the new one will have the data. You have switched the metadata for the two tables (instant).
Drop the original (now-empty table), exec sys.sp_rename to rename the various schema objects back to the original names, and then you can recreate your foreign keys.
For example, given:
CREATE TABLE Original
(
Id INT IDENTITY PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value ON Original (Value);
INSERT INTO Original
SELECT 'abcd'
UNION ALL
SELECT 'defg';
You can do the following:
--create new table with no IDENTITY
CREATE TABLE Original2
(
Id INT PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value2 ON Original2 (Value);
--data before switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;
ALTER TABLE Original SWITCH TO Original2;
--data after switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;
--clean up
IF NOT EXISTS (SELECT * FROM Original) DROP TABLE Original;
EXEC sys.sp_rename 'Original2.IX_Original_Value2', 'IX_Original_Value', 'INDEX';
EXEC sys.sp_rename 'Original2', 'Original', 'OBJECT';
UPDATE Original
SET Id = Id + 1;
SELECT *
FROM Original;
For the record, as this has become increasingly popular, I have wanted to track down the original source (I didn't think of it myself), but of course I've long forgotten where I found the original idea. It may have been here; this was the only one I could find predating this answer (time flies, boys and girls): https://social.technet.microsoft.com/wiki/contents/articles/17738.sql-server-quick-way-to-remove-the-identity-property.aspx
This gets messy with foreign and primary key constraints, so here's some scripts to help you on your way:
First, create a duplicate column with a temporary name:
alter table yourTable add tempId int NOT NULL default -1;
update yourTable set tempId = id;
Next, get the name of your primary key constraint:
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'yourTable';
Now try drop the primary key constraint for your column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
If you have foreign keys, it will fail, so if so drop the foreign key constraints. KEEP TRACK OF WHICH TABLES YOU RUN THIS FOR SO YOU CAN ADD THE CONSTRAINTS BACK IN LATER!!!
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'otherTable';
alter table otherTable drop constraint fk_otherTable_yourTable;
commit;
..
Once all of your foreign key constraints have been removed, you'll be able to remove the PK constraint, drop that column, rename your temp column, and add the PK constraint to that column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
alter table yourTable drop column id;
EXEC sp_rename 'yourTable.tempId', 'id', 'COLUMN';
ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id)
commit;
Finally, add the FK constraints back in:
alter table otherTable add constraint fk_otherTable_yourTable foreign key (yourTable_id) references yourTable(id);
..
El Fin!
I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.
Make a new column
alter table users add newusernum int;
Copy values over
update users set newusernum=usernum;
Drop the old column
alter table users drop column usernum;
Rename the new column to the old column name
EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';
Following script removes Identity field for a column named 'Id'
Hope it helps.
BEGIN TRAN
BEGIN TRY
EXEC sp_rename '[SomeTable].[Id]', 'OldId';
ALTER TABLE [SomeTable] ADD Id int NULL
EXEC ('UPDATE [SomeTable] SET Id = OldId')
ALTER TABLE [SomeTable] NOCHECK CONSTRAINT ALL
ALTER TABLE [SomeTable] DROP CONSTRAINT [PK_constraintName];
ALTER TABLE [SomeTable] DROP COLUMN OldId
ALTER TABLE [SomeTable] ALTER COLUMN [Id] INTEGER NOT NULL
ALTER TABLE [SomeTable] ADD CONSTRAINT PK_JobInfo PRIMARY KEY (Id)
ALTER TABLE [SomeTable] CHECK CONSTRAINT ALL
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
SELECT ERROR_MESSAGE ()
END CATCH
Bellow code working as fine, when we don't know identity column name.
Need to copy data into new temp table like Invoice_DELETED.
and next time we using:
insert into Invoice_DELETED select * from Invoice where ...
SELECT t1.*
INTO Invoice_DELETED
FROM Invoice t1
LEFT JOIN Invoice ON 1 = 0
--WHERE t1.InvoiceID = #InvoiceID
For more explanation see:
https://dba.stackexchange.com/a/138345/101038
ALTER TABLE tablename add newcolumn int
update tablename set newcolumn=existingcolumnname
ALTER TABLE tablename DROP COLUMN existingcolumnname;
EXEC sp_RENAME 'tablename.oldcolumn' , 'newcolumnname', 'COLUMN'
However above code works only if no primary-foreign key relation
In SQL Server you can turn on and off identity insert like this:
SET IDENTITY_INSERT table_name ON
-- run your queries here
SET IDENTITY_INSERT table_name OFF
Just for someone who have the same problem I did.
If you just want to make some insert just once you can do something like this.
Lets suppose you have a table with two columns
ID Identity (1,1) | Name Varchar
and want to insert a row with the ID = 4. So you Reseed it to 3 so the next one is 4
DBCC CHECKIDENT([YourTable], RESEED, 3)
Make the Insert
INSERT INTO [YourTable]
( Name )
VALUES ( 'Client' )
And get your seed back to the highest ID, lets suppose is 15
DBCC CHECKIDENT([YourTable], RESEED, 15)
Done!
I had the same requirement, and you could try this way, which I personally recommend you, please manually design your table and generate the script, and what I did below was renaming the old table and also its constraint for backup.
/* 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
ALTER TABLE dbo.SI_Provider_Profile
DROP CONSTRAINT DF_SI_Provider_Profile_SIdtDateTimeStamp
GO
ALTER TABLE dbo.SI_Provider_Profile
DROP CONSTRAINT DF_SI_Provider_Profile_SIbHotelPreLoaded
GO
CREATE TABLE dbo.Tmp_SI_Provider_Profile
(
SI_lProvider_Profile_ID int NOT NULL,
SI_lSerko_Integrator_Token_ID int NOT NULL,
SI_sSerko_Integrator_Provider varchar(50) NOT NULL,
SI_sSerko_Integrator_Profile varchar(50) NOT NULL,
SI_dtDate_Time_Stamp datetime NOT NULL,
SI_lProvider_ID int NULL,
SI_sDisplay_Name varchar(10) NULL,
SI_lPurchased_From int NULL,
SI_sProvider_UniqueID varchar(255) NULL,
SI_bHotel_Pre_Loaded bit NOT NULL,
SI_sSiteName varchar(255) NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile SET (LOCK_ESCALATION = TABLE)
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile ADD CONSTRAINT
DF_SI_Provider_Profile_SIdtDateTimeStamp DEFAULT (getdate()) FOR SI_dtDate_Time_Stamp
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile ADD CONSTRAINT
DF_SI_Provider_Profile_SIbHotelPreLoaded DEFAULT ((0)) FOR SI_bHotel_Pre_Loaded
GO
IF EXISTS(SELECT * FROM dbo.SI_Provider_Profile)
EXEC('INSERT INTO dbo.Tmp_SI_Provider_Profile (SI_lProvider_Profile_ID, SI_lSerko_Integrator_Token_ID, SI_sSerko_Integrator_Provider, SI_sSerko_Integrator_Profile, SI_dtDate_Time_Stamp, SI_lProvider_ID, SI_sDisplay_Name, SI_lPurchased_From, SI_sProvider_UniqueID, SI_bHotel_Pre_Loaded, SI_sSiteName)
SELECT SI_lProvider_Profile_ID, SI_lSerko_Integrator_Token_ID, SI_sSerko_Integrator_Provider, SI_sSerko_Integrator_Profile, SI_dtDate_Time_Stamp, SI_lProvider_ID, SI_sDisplay_Name, SI_lPurchased_From, SI_sProvider_UniqueID, SI_bHotel_Pre_Loaded, SI_sSiteName FROM dbo.SI_Provider_Profile WITH (HOLDLOCK TABLOCKX)')
GO
-- Rename the primary key constraint or unique key In SQL Server constraints such as primary keys or foreign keys are objects in their own right, even though they are dependent upon the "containing" table.
EXEC sp_rename 'dbo.SI_Provider_Profile.PK_SI_Provider_Profile', 'PK_SI_Provider_Profile_Old';
GO
-- backup old table in case of
EXECUTE sp_rename N'dbo.SI_Provider_Profile', N'SI_Provider_Profile_Old', 'OBJECT'
GO
EXECUTE sp_rename N'dbo.Tmp_SI_Provider_Profile', N'SI_Provider_Profile', 'OBJECT'
GO
ALTER TABLE dbo.SI_Provider_Profile ADD CONSTRAINT
PK_SI_Provider_Profile PRIMARY KEY NONCLUSTERED
(
SI_lProvider_Profile_ID
) WITH( PAD_INDEX = OFF, FILLFACTOR = 90, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT TRANSACTION
ALTER TABLE TABLE_NAME MODIFY (COLUMN_NAME DROP IDENTITY);
I'm looking at the AdventureWorks sample database for SQL Server 2008, and I see in their creation scripts that they tend to use the following:
ALTER TABLE [Production].[ProductCostHistory] WITH CHECK ADD
CONSTRAINT [FK_ProductCostHistory_Product_ProductID] FOREIGN KEY([ProductID])
REFERENCES [Production].[Product] ([ProductID])
GO
followed immediately by :
ALTER TABLE [Production].[ProductCostHistory] CHECK CONSTRAINT
[FK_ProductCostHistory_Product_ProductID]
GO
I see this for foreign keys (as here), unique constraints and regular CHECK constraints; DEFAULT constraints use the regular format I am more familiar with such as:
ALTER TABLE [Production].[ProductCostHistory] ADD CONSTRAINT
[DF_ProductCostHistory_ModifiedDate] DEFAULT (getdate()) FOR [ModifiedDate]
GO
What is the difference, if any, between doing it the first way versus the second?
The first syntax is redundant - the WITH CHECK is default for new constraints, and the constraint is turned on by default as well.
This syntax is generated by the SQL management studio when generating sql scripts -- I'm assuming it's some sort of extra redundancy, possibly to ensure the constraint is enabled even if the default constraint behavior for a table is changed.
To demonstrate how this works--
CREATE TABLE T1 (ID INT NOT NULL, SomeVal CHAR(1));
ALTER TABLE T1 ADD CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED (ID);
CREATE TABLE T2 (FKID INT, SomeOtherVal CHAR(2));
INSERT T1 (ID, SomeVal) SELECT 1, 'A';
INSERT T1 (ID, SomeVal) SELECT 2, 'B';
INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A1';
INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A2';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B1';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B2';
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C1'; --orphan
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C2'; --orphan
--Add the FK CONSTRAINT will fail because of existing orphaned records
ALTER TABLE T2 ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --fails
--Same as ADD above, but explicitly states the intent to CHECK the FK values before creating the CONSTRAINT
ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --fails
--Add the CONSTRAINT without checking existing values
ALTER TABLE T2 WITH NOCHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --succeeds
ALTER TABLE T2 CHECK CONSTRAINT FK_T2_T1; --succeeds since the CONSTRAINT is attributed as NOCHECK
--Attempt to enable CONSTRAINT fails due to orphans
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1; --fails
--Remove orphans
DELETE FROM T2 WHERE FKID NOT IN (SELECT ID FROM T1);
--Enabling the CONSTRAINT succeeds
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1; --succeeds; orphans removed
--Clean up
DROP TABLE T2;
DROP TABLE T1;
Further to the above excellent comments about trusted constraints:
select * from sys.foreign_keys where is_not_trusted = 1 ;
select * from sys.check_constraints where is_not_trusted = 1 ;
An untrusted constraint, much as its name suggests, cannot be trusted to accurately represent the state of the data in the table right now. It can, however, but can be trusted to check data added and modified in the future.
Additionally, untrusted constraints are disregarded by the query optimiser.
The code to enable check constraints and foreign key constraints is pretty bad, with three meanings of the word "check".
ALTER TABLE [Production].[ProductCostHistory]
WITH CHECK -- This means "Check the existing data in the table".
CHECK CONSTRAINT -- This means "enable the check or foreign key constraint".
[FK_ProductCostHistory_Product_ProductID] -- The name of the check or foreign key constraint, or "ALL".
WITH NOCHECK is used as well when one has existing data in a table that doesn't conform to the constraint as defined and you don't want it to run afoul of the new constraint that you're implementing...
WITH CHECK is indeed the default behaviour however it is good practice to include within your coding.
The alternative behaviour is of course to use WITH NOCHECK, so it is good to explicitly define your intentions. This is often used when you are playing with/modifying/switching inline partitions.
Foreign key and check constraints have the concept of being trusted or untrusted, as well as being enabled and disabled. See the MSDN page for ALTER TABLE for full details.
WITH CHECK is the default for adding new foreign key and check constraints, WITH NOCHECK is the default for re-enabling disabled foreign key and check constraints. It's important to be aware of the difference.
Having said that, any apparently redundant statements generated by utilities are simply there for safety and/or ease of coding. Don't worry about them.
Here is some code I wrote to help us identify and correct untrusted CONSTRAINTs in a DATABASE. It generates the code to fix each issue.
;WITH Untrusted (ConstraintType, ConstraintName, ConstraintTable, ParentTable, IsDisabled, IsNotForReplication, IsNotTrusted, RowIndex) AS
(
SELECT
'Untrusted FOREIGN KEY' AS FKType
, fk.name AS FKName
, OBJECT_NAME( fk.parent_object_id) AS FKTableName
, OBJECT_NAME( fk.referenced_object_id) AS PKTableName
, fk.is_disabled
, fk.is_not_for_replication
, fk.is_not_trusted
, ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( fk.parent_object_id), OBJECT_NAME( fk.referenced_object_id), fk.name) AS RowIndex
FROM
sys.foreign_keys fk
WHERE
is_ms_shipped = 0
AND fk.is_not_trusted = 1
UNION ALL
SELECT
'Untrusted CHECK' AS KType
, cc.name AS CKName
, OBJECT_NAME( cc.parent_object_id) AS CKTableName
, NULL AS ParentTable
, cc.is_disabled
, cc.is_not_for_replication
, cc.is_not_trusted
, ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( cc.parent_object_id), cc.name) AS RowIndex
FROM
sys.check_constraints cc
WHERE
cc.is_ms_shipped = 0
AND cc.is_not_trusted = 1
)
SELECT
u.ConstraintType
, u.ConstraintName
, u.ConstraintTable
, u.ParentTable
, u.IsDisabled
, u.IsNotForReplication
, u.IsNotTrusted
, u.RowIndex
, 'RAISERROR( ''Now CHECKing {%i of %i)--> %s ON TABLE %s'', 0, 1'
+ ', ' + CAST( u.RowIndex AS VARCHAR(64))
+ ', ' + CAST( x.CommandCount AS VARCHAR(64))
+ ', ' + '''' + QUOTENAME( u.ConstraintName) + ''''
+ ', ' + '''' + QUOTENAME( u.ConstraintTable) + ''''
+ ') WITH NOWAIT;'
+ 'ALTER TABLE ' + QUOTENAME( u.ConstraintTable) + ' WITH CHECK CHECK CONSTRAINT ' + QUOTENAME( u.ConstraintName) + ';' AS FIX_SQL
FROM Untrusted u
CROSS APPLY (SELECT COUNT(*) AS CommandCount FROM Untrusted WHERE ConstraintType = u.ConstraintType) x
ORDER BY ConstraintType, ConstraintTable, ParentTable;
Dare I say it, it feels like it might be an SSMS (inverted logic) bug; in that the explicit inclusion/use of the 'WITH CHECK' would be needed for the 2nd (existing/reenabled constraint) statement, not the first (new/'with-check' defaulted).
I'm wondering whether they've just applied the generation of the 'WITH CHECK' clause to the wrong SQL statement / the 1st T-SQL statement rather than the 2nd one - assuming they're trying to default the use of the check for both scenarios - for both a new constraint or (the reenabling of) an existing one.
(Seems to make sense to me, as the longer a check constraint is disabled, the theoretically increased chance that broken/check-constraint-invalid data might have crept-in in the meantime.)