How to alter primary key in table for snowflake? - snowflake-cloud-data-platform

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);

Related

ALTER COLUMN datatype to NOT NULL without dropping index and manually recreating it

I have a table with foreign key:
CREATE TABLE [dbo].[MyTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ForeignId] [int] NULL)
ALTER TABLE [dbo].[MyTable] WITH CHECK ADD CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY([ForeignId])
REFERENCES [dbo].[OtherTable] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ExpedíciaVýrobky] CHECK CONSTRAINT [FK_MyTable_OtherTable]
I would like to alter the ForeignId datatype to NOT NULL:
ALTER TABLE [dbo].[MyTable] ALTER COLUMN ForeignId INT NOT NULL;
This requires to drop the FK contraint and recreate it.
Is it possible to do so without manually scripting ALTER TABLE CHECK ADD CONSTRAINT ... FOREIGN KEY bla bla with all the details?
For example, if somebody edited the ON DELETE meanwhile, I don't wont to override this change.
EDIT:
In ideal world, I would like to have stored procedure SpAlterColumnToNotNULL(tablename, columnname), that would do the dropping and recreating indexes automatically.

How to alter type of a column who is references as Foreign key in other table?

I want to change the dataType of primary key from varchar to bigint.
I tried following command.
ALTER TABLE dbo.Company
ALTER COLUMN Id bigint
but it is not working as this column is referenced as the foreign key in other tables.
How can i change its type without loosing data of the table through Sql Query?
There are several steps to accomplish this. But the main thing, is that first you'll have to drop the key.
First drop the primary (change name_of_primary_key, with yours real):
ALTER TABLE dbo.Company DROP CONSTRAINT name_of_primary_key;
Change the data type (replace length with your desired):
alter table table alter column foreign_key_column bigint(length)
Then drop the foreign key from other tables (make this for every table, and replace the two arguments, with your real from the db):
ALTER TABLE table DROP FOREIGN KEY foreign_key_column;
Now, you change the data type of the foreign key column(replace length with your desired):
alter table table alter column foreign_key_column bigint(length);

SQL Server : rename primary key

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;

Is it possible to implement self referencing foreign key with update cascade in SQL Server?

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?

Add primary key column in SQL 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.

Resources