I have a table doc.MyTable which I want to deprecate by renaming to doc._MyTable. I then want to create a new doc.MyTable with the same primary key that the old doc.MyTable had. The problem is that SQL Server says that primary key already exists. So that means I need to rename the old primary key too.
I tried the following:
EXEC SP_RENAME 'doc.MyTable', '_MyTable'
-- Method 1
EXEC SP_RENAME 'PK_MyTable', 'PK__MyTable'
-- Method 2
ALTER TABLE [doc].[_MyTable] DROP CONSTRAINT [PK_MyTable]
ALTER TABLE [doc].[_MyTable] ADD CONSTRAINT [PK__MyTable]
PRIMARY KEY CLUSTERED
(
[document_id] ASC,
[line_id] ASC,
[sub_line_id] ASC
)
-- Create new table
CREATE TABLE [doc].[MyTable] (
... columns
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED (
... key columns
)
... extra conditions
Method 1 throws this error:
No item by the name of 'PK_MyTable' could be found in the current database 'db_dev', given that #itemtype was input as '(null)'.
While method 2 throws this:
Violation of PRIMARY KEY constraint 'PK_MyTable'. Cannot insert duplicate key in object 'PK.MyTable'. The duplicate key value is (10358930, 336000, 0).`
When I try to create the new primary key for the new table.
I'm only using one of the two "Methods" at a time. How do I fix the issue?
Try following solution:
EXEC sp_rename '[TableSchema].[TableName].[ConstraintName]', 'NewConstraintName'
Example:
EXEC sp_rename '[doc].[_MyTable].[PK_MyTable]', '[PK__MyTable]'
When renaming your primary key, prefix the primary key name with the schema and table name like so:
create schema doc authorization dbo;
go
create table doc.MyTable (
id int not null
, constraint pk_MyTable primary key clustered (Id)
);
exec sp_rename N'doc.MyTable.pk_MyTable', N'pk__MyTable';
exec sp_rename N'doc.MyTable', N'_MyTable', N'object';
create table doc.MyTable (
id int not null
, constraint pk_MyTable primary key clustered (Id)
);
rextester demo: http://rextester.com/OBIB87116
If you were using the default schema dbo, you would not need to prefix the schema and table name to rename the primary key with sp_rename.
Cant you delete it from your original table and re-create it with the name you want?
ALTER TABLE dbo.YourOldTable
DROP CONSTRAINT YourConstraintname;
Related
I created a table with a primary key. I would like to alter a primary key.
I thought using Alter Table command is the solution, but not successful.
ALTER TABLE "tablename" ALTER PRIMARY KEY (col1,col2);
Could you please help me how to alter primary key using SQL statement?
You can add primary key constraint to a column but cannot alter an existing one.
https://docs.snowflake.com/en/sql-reference/sql/create-table-constraint.html#out-of-line-unique-primary-foreign-key
Drop and recreate the primary key. Here's an example:
ALTER TABLE "tablename" DROP CONSTRAINT "pk_name";
ALTER TABLE "tablename" ADD CONSTRAINT "pk_name" PRIMARY KEY (col1,col2);
In case you've multiple primary keys, it's done like this:
ALTER TABLE SCHEMA.TABLE DROP PRIMARY KEY;
ALTER TABLE SCHEMA.TABLE ADD CONSTRAINT CONSTRAINT_NAME PRIMARY KEY (col1, col1, ..., coln);
I have a table with the following fields:
searchID ( I have set this as a primary key )
SearchText nvarchar(MAX)
.......
and so on
I want to make SearchText also as an additional primary field. How should this be done? Is that a good procedure to make two primary columns for a table?
It's impossible to have more than one primary key on one table and store unique values.
Your primary key must be as short as possible.
If you need to keep unique data in other column, you can create unique key on this column:
CREATE TABLE dbo.Table
(
SearchText nvarchar(MAX)NOT NULL,
CONSTRAINT AK_SearchText UNIQUE(SearchText)
);
Or with management studio:
You can create composite key as below
create table myTable
(
SearchId int not null,
SearchText nvharchar not null
)
GO
-- Add Constraint
ALTER TABLE myTable
ADD CONSTRAINT pk_myConstraint PRIMARY KEY (SearchId ,SearchText)
GO
I've this table:
CREATE TABLE [SomeTable](
[Id] int NOT NULL
,[SomeColumn] varchar(50) NULL
,[ParentId] int NULL CONSTRAINT [PK_SomeTable] PRIMARY KEY CLUSTERED ([Id] ASC)
ALTER TABLE [SomeTable] WITH CHECK ADD CONSTRAINT
[FK_SomeTable_SomeTable] FOREIGN KEY([ParentId])
REFERENCES [SomeTable] ([Id])
ALTER TABLE [SomeTable] CHECK CONSTRAINT [FK_SomeTable_SomeTable]
Sql Server does not allow me to put ON UPDATE CASCADE.
Is there any way to get that if i update Id column, all child rows ParentId get updated too?
I'm new to sqlplus and was trying to run a sql script that creates a few tables, but once I try to run it, it gives me an error saying that the table or view doesnt exist and I dont know how to fix this error.
My script is:
drop table Borrower;
create table Borrower (
bid char(100) not null,
password char(100) not null,
name char(100) null,
address char(100) null,
phone char(100) null,
emailAddress char(100) null,
sinOrStNo char(100) null,
expiryDate date null,
--type ENUM('student','faculty','staff'),
type char(100) not null,
--CONSTRAINT Btype_check CHECK (type IN ('student','faculty','staff')),
FOREIGN KEY (type) references BorrowerType(type),
PRIMARY KEY (bid));
grant select on Borrower to public;
"unique/primary keys in table referenced by foreign keys "
Data integrity is crucial to a properly run database so Oracle will not let us drop a table if its primary key is referenced by another table's foreign key. So it hurls ORA-02449.
So, given this set up:
create table t_parent (
id number not null
, constraint tp_pk primary key (id)
);
create table t_child (
id number not null
, p_id number not null
, constraint tc_pk primary key (id)
, constraint tc_tp_fk foreign key (p_id)
references t_parent (id)
);
There are three ways to drop table t_parent.
run drop table t_child first: no child table, no foreign key.
Remove the blocking foreign key: alter table t_child drop constraint tc_pc_fk.
A variant on the previous one, let the database figure out the foreign keys:
drop table t_parent cascade constraints.
The first option is the most proper, because it leaves the database in a valid state (no tables, no possibility of data integrity corruption). The valid use for the third approach is a script which razes all the tables from a schema: it's easy to generate such a script from the data dictionary.
The order that you drop or create tables are important because if you have foreign keys referencing another table, you cant delete that table before deleting your own table.
In this example, the Borrower table has to be dropped before the BorrowerType table.
I am student of RDBMS.
I have very basic question let say I have one existing Table in SQL server. What will be script to alter table.
Drop Column 'RowId' if exist.
Drop contraint if exist.
Add one new column 'RowId' into table.
Make this column as primary key.
Autoincrement type int.
In SQL Server 2005 or newer, you could use this script:
-- drop PK constraint if it exists
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.YourTable') AND Name = 'PK_YourTable')
ALTER TABLE dbo.YourTable
DROP CONSTRAINT PK_YourTable
GO
-- drop column if it already exists
IF EXISTS (SELECT * FROM sys.columns WHERE Name = 'RowId' AND object_id = OBJECT_ID('dbo.YourTable'))
ALTER TABLE dbo.YourTable DROP COLUMN RowId
GO
-- add new "RowId" column, make it IDENTITY (= auto-incrementing)
ALTER TABLE dbo.YourTable
ADD RowId INT IDENTITY(1,1)
GO
-- add new primary key constraint on new column
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable
PRIMARY KEY CLUSTERED (RowId)
GO
Of course, this script may still fail, if other tables are referencing this dbo.YourTable using foreign key constraints onto the pre-existing RowId column...
Update: and of course, anywhere I use dbo.YourTable or PK_YourTable, you have to replace those placeholder with the actual table / constraint names from your own database (you didn't mention what they were, in your question.....)
Note: this answer was added before questions update
Add new column (note: you can only have one IDENTITY column per table)
Drop old primary key
Add new primary key
Drop old column if needed
Sample script:
CREATE TABLE whatever (
OldPKColumn uniqueidentifier NOT NULL,
CONSTRAINT PK_whatever PRIMARY KEY (OldPKColumn)
)
ALTER TABLE whatever
ADD RowId int NOT NULL IDENTITY (1,1);
ALTER TABLE whatever
DROP CONSTRAINT PK_whatever;
ALTER TABLE whatever WITH CHECK
ADD CONSTRAINT PK_whatever PRIMARY KEY CLUSTERED (RowId);
ALTER TABLE whatever
DROP COLUMN oldPKcolumn;
And a random thought... are you trying to reset an IDENTITY column?
If so, then use DBCC CHECKIDENT
Just a comment to improve these great answers (can't use comments yet - I'm one reputation point away from that privilege) and as future reference for myself:
A new IDENTITY (autonumber) column can be added and made the primary key in a single statement as well:
ALTER TABLE [TableName] ADD [ColumnName] int IDENTITY PRIMARY KEY;
I prefer not to bother with constraint names when it doesn't help.
You can specify seed (and increment) values between parantheses after the IDENTITY keyword.