Snowflake Primary key using alter statement - snowflake-cloud-data-platform

when I was adding primary key to snowflake table I saw something weird.
When I ran a query
ALTER TABLE "TESTSCHEMA".table1 ADD PRIMARY KEY (ID);
Above query works as expected. But when I tried to run
ALTER TABLE IF EXISTS "TESTSCHEMA".table1 ADD PRIMARY KEY (ID);
Query was returning error error line 0 at position 0 invalid identifier 'TOK_IF_EXISTS'
Is this a bug or Am I doing something wrong?

Adding a primary key to the same column is expected to result in an error as provided below.
create table "TESTSCHEMA".table (id number);
--Statement executed successfully.
ALTER TABLE "TESTSCHEMA".table ADD PRIMARY KEY (ID);
--Statement executed successfully.
ALTER TABLE "TESTSCHEMA".table ADD PRIMARY KEY (ID);
--SQL compilation error: primary key already exists for table 'TABLE'
create table "TESTSCHEMA"."table1" (id number);
--Statement executed successfully.
ALTER TABLE "TESTSCHEMA"."table1" ADD PRIMARY KEY (ID);
--Statement executed successfully.
ALTER TABLE "TESTSCHEMA"."table1" ADD PRIMARY KEY (ID);
---SQL compilation error: primary key already exists for table 'table1'
The test case shared by you with the error details can be reported to Snowflake for validation

According to docs, it looks like a bug. Could you raise snowflake support case so that the behaviour can be validated? Thanks,
https://docs.snowflake.com/en/sql-reference/sql/alter-table.html

Related

Why does violation of PRIMARY KEY constraint return error code 2627 not 2601 in SQL Server?

I am confused for a while since the Document point out:
When you create a PRIMARY KEY constraint, a unique clustered index on
the column or columns is automatically created if a clustered index on
the table does not already exist and you do not specify a unique
nonclustered index. The primary key column cannot allow NULL values.
I have a table in SQL server with a PRIMARY KEY constraint. According to the above point,a unique clustered index on the column or columns is automatically created since i did't create any clustered in the table.
I learned 2601 Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls' from Database Engine Errors.
My question is that why SQL server return error code 2627 and not 2601 when I try to insert duplicate value in primary key column into my table which have a unique clustered index on primary key? Is it because 2627 has a higher priority than 2601 or what?
Can someone please give me some advice or help? Thanks.
A Primary Key, at least on SQL Server, is a type of Constraint. As a result when you create a Primary Key it is both a (unique) Index and a Constraint. Both error 2627 and 2601 have the same severity, so it appears that SQL Server will return the higher error code (as both a unique index and constraint were violated).
From testing, you'll only get the error 2601 is the column has a unique index that is violated, but does not have a constraint. Most likely, therefore, you'll see this on a conditional unique index.
Take the below examples:
USE Sandbox;
GO
--First sample table with primary key (Clustered)
CREATE TABLE dbo.TestTable1 (ID int PRIMARY KEY);
GO
--inserts fine
INSERT INTO dbo.TestTable1
VALUES(1);
GO
--Errors with code 2627
INSERT INTO dbo.TestTable1
VALUES(1);
GO
--Create second sample table, with unique Constraint
CREATE TABLE dbo.TestTable2(ID int,
CONSTRAINT U_ID UNIQUE(ID));
GO
--Inserts fine
INSERT INTO dbo.TestTable2
VALUES(1);
GO
--Errors with code 2627
INSERT INTO dbo.TestTable2
VALUES(1);
GO
--Create third sample table
CREATE TABLE dbo.TestTable3(ID int);
--Create unique index, without Constraint
CREATE UNIQUE INDEX ID_UX ON dbo.TestTable3(ID);
GO
--Inserts fine
INSERT INTO dbo.TestTable3
VALUES(1);
GO
--Errors with code 2601
INSERT INTO dbo.TestTable3
VALUES(1);
GO
--Clean up
DROP TABLE dbo.TestTable1
DROP TABLE dbo.TestTable2
DROP TABLE dbo.TestTable3
Note that only the last insert fails with error 2601; the other 2 fail with 2627.

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;

Delete foreign key with primary key reference

I tried many forums but was not satisfied - I have a table that has a primary key and foreign key relation.
I have to delete table rows with primary key so I need to remove the constraints before deleting.
I used:
delete from [docd_metadata].[docd_metadata].[STATEMENT_IMAGES]
where [statement_image_id]= 05291520275
I got error:
The DELETE statement conflicted with the REFERENCE constraint "fk_stmnt_image_StmntImageId". The conflict occurred in database "docd_metadata", table "docd_metadata.STATEMENT_CAMPAIGN", column 'STATEMENT_IMAGE_ID'.
so I tried :
ALTER TABLE[docd_metadata].[docd_metadata].[STATEMENT_IMAGES]
DROP CONSTRAINT [fk_stmnt_image_StmntImageId]
Now I am getting :
Constraint 'fk_stmnt_image_StmntImageId' does not belong to table 'STATEMENT_IMAGES'
Schema:
Also:
Any suggestion please?
If you really closely read the error message, it's clear that the FK constraint is on table docd_metadata.STATEMENT_CAMPAIGN and not on STATEMENT_IMAGES - so therefore, you must use this SQL to drop the FK constraint:
ALTER TABLE [docd_metadata].[STATEMENT_CAMPAIGN]
DROP CONSTRAINT [fk_stmnt_image_StmntImageId]
The FK goes from table [docd_metadata].[STATEMENT_CAMPAIGN] (column STATEMENT_IMAGE_ID) to [docd_metadata].[STATEMENT_IMAGES] - one table has the primary key, which another table references via its foreign key.

Update even though using constraints

I'm trying to update a value (small spelling error) in the SQL Server 2014 database.
I do like this:
update t_Table set funID = 'References' where funID = 'Referencies'
When doing this I get the error
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_t_Table_Language_t_Table". The conflict occurred in database "db", table "dbo.t_Table".
If updating the foreign key, I get a similar error.
Is there any way to update all values at the same time?
I have a vague memory of someone showing a way to do this in management studio but I do not recall how.
Enable update cascade on the foreign key
ALTER TABLE t_Table_Language DROP CONSTRAINT FK_t_Table_Language_t_Table
ALTER TABLE t_Table_Language ADD CONSTRAINT FK_t_Table_Language_t_Table
FOREIGN KEY (funID) REFERENCES t_Table(funID)
ON UPDATE CASCADE
EDIT:
Or the other way around, i'm not sure which table has the foreing key
ALTER TABLE t_Table DROP CONSTRAINT FK_t_Table_Language_t_Table
ALTER TABLE t_Table ADD CONSTRAINT FK_t_Table_Language_t_Table
FOREIGN KEY (funID) REFERENCES t_Table_Language(funID)
ON UPDATE CASCADE
Then do the update on the referenced table (the master table).
UPDATE t_Table_Language
SET funID = 'References'
WHERE funID = 'Referencies'

Adding constraint conflicts with itself, even though it doesn't exist yet

I'm adding delete cascading to a Table. The Clone table has a column DeviceID that is a foreign key to the Device table's DeviceID column. So the SQL script drops the original FK constraint, and attempts to add the new one:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'FK_Clone_Device'
)
BEGIN
ALTER TABLE Clone
DROP CONSTRAINT FK_Clone_Device
END
IF NOT EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'FK_Clone_Device_Cascade'
)
BEGIN
ALTER TABLE Clone
ADD CONSTRAINT FK_Clone_Device_Cascade
FOREIGN KEY (DeviceID) REFERENCES Device(DeviceID) ON DELETE CASCADE
END
When I run this script, I get the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Clone_Device_Cascade". The conflict occurred in database "DevelopmentDB", table "dbo.Device", column 'DeviceID'.
Maybe I'm misunderstanding the error message, but it sounds like it's conflicting with itself. I'm confused that it happened on the Device table though.
There is an index in the Clone table on DeviceID. Would that matter?
This is on SQL SERVER R2 (Azure)
Sounds like you currently have data in the table that would violate the FK you are trying to create. One way to test this is to add "WITH (NOCHECK)" to the ALTER TABLE statement and see if it lets you create the constraint.
If it does let you create the constraint with NOCHECK, you can either leave it that way and the constraint will only be used to test future inserts/updates, or you can investigate your data to fix the FK violations.
So your example would be:
ALTER TABLE Clone WITH NOCHECK
ADD CONSTRAINT FK_Clone_Device_Cascade
FOREIGN KEY (DeviceID) REFERENCES Device(DeviceID) ON DELETE CASCADE

Resources