Phantom Table being created in Teradata - sql

I'm using Teradata 16.20.05.01 to run the following script:
create table t1(v int not null);
create table t2(w int null);
alter table t1 add constraint pk primary key (v);
alter table t2 add constraint t2_fk foreign key (w) references t1 (v);
After adding the foreign key, I suddenly get one excess table in my schema:
select TableName, RequestText
from "DBC".Tables
where DatabaseName = 'test'
and (TableName like 't1%' or TableName like 't2%')
Output:
TableName |RequestText |
----------|----------------------------------------------------------------------|
t1 |alter table t1 add constraint pk primary key (v) |
t2 |create table t2(w int null) |
T2_0 |alter table t2 add constraint t2_fk foreign key (w) references t1 (v) |
This is especially annoying when re-creating that foreign key:
alter table t2 drop constraint t2_fk;
alter table t2 add constraint t2_fk foreign key (w) references t1 (v);
Which isn't possible because of:
SQL Error [5303] [HY000]: [Teradata Database] [TeraJDBC 15.00.00.33] [Error 5303] [SQLState HY000] Error table 'TEST.t2_0' already exists.
Workaround:
The problem does not appear when using inline constraint definitions
create table t1(v int not null, constraint pk primary key (v));
create table t2(w int null, constraint t2_fk foreign key (w) references t1 (v));
Is this a known issue? Is there a reliable workaround?

This is documented behaviour, when you add a Foreign Key to an existing table there's an error table created and all all rows violating the constraint are copied into it. And it's not dropped automatically after the ALTER.
The workaround is simple: Don't use Standard Foreign Keys, you will hardly find any site using it. Switch to Batch FKs, i.e. REFERENCES WITH CHECK OPTION, which applies the check on a request level (not row by row), or to a Soft/Dummy FK, REFERENCES WITH NO CHECK OPTION, which simply defined the constraint without enforcing it (you must check for PK/FK violations in your load scripts anyway).

Related

SQL Server : multi CASCADE Operation

I have two tables, and I want HEDE2 columns as FOREIGN KEY REFERENCES by HEDE table. FOR creating second table it will not allow because its having warning:
More than one key specified in column level FOREIGN KEY constraint, table 'HEDE2'.
But when I tried to ALTER TABLE HEDE2 for FOREIGN KEY it allows me to do that. Is anybody knows WHY this happens. Is this a bug?
CREATE TABLE cascde.HEDE
(
HedeID INT,
HedeID2 INT,
HedeID3 INT
CONSTRAINT PK_HEDE
PRIMARY KEY (HedeID, HedeID2, HedeID3)
)
GO
CREATE TABLE HEDE2
(
Hede2ID INT PRIMARY KEY IDENTITY(1,1) ,
HedeID INT,
HedeID2 INT,
HedeID3 INT
CONSTRAINT FK_HedeID
FOREIGN KEY (HedeID, Hede2ID, HedeID3)
REFERENCES cascde.HEDE (HedeID, HedeID2, HedeID3)
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
Altering table HEDE 2 for foreign key. This allows me to do that:
ALTER TABLE cascde.HEDE2
ADD CONSTRAINT FK_HEDE
FOREIGN KEY(HedeID, HedeID2, HedeID3)
REFERENCES cascde.HEDE (HedeID, HedeID2, HedeID3)
ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
You're missing a comma (,) after HedeID3 INT in the CREATE TABLE version.

CASCADE behaviour on the drop of a foreign key

I am not clear about what happens when a "foreign key constraint" is deleted specifying the option CASCADE.
For instance, consider this command
ALTER TABLE table1 DROP CONSTRAINT foreignKeyToTable2 CASCADE.
What the option CASCADE is supposed to do in this case? What would happen if I omitted it? And if I wrote RESTRICT instead of CASCADE?
Note: this example of query is excerpted from "Ramez Elmasri, Shamkant B. Navathe - Fundamentals of database systems, end of chapter 5".
The cascade option to drop a constraint is only needed when dropping primary keys, not when dropping a foreign key.
Consider this example in Postgres:
create table t1 (id integer, constraint pk_one primary key (id));
create table t2 (id integer primary key, id1 integer references t1);
When you try to run:
alter table t1 drop constraint pk_one;
You get:
ERROR: cannot drop constraint pk_one on table t1 because other objects depend on it
Detail: constraint t2_id1_fkey on table t2 depends on index pk_one
Hint: Use DROP ... CASCADE to drop the dependent objects too.
If you run:
alter table t1 drop constraint pk_one cascade;
you get:
NOTICE: drop cascades to constraint t2_id1_fkey on table t2
Telling you that the foreign key that needed the primary key was dropped as well.
Note that not all DBMS support a cascading drop. Postgres and Oracle do.
MySQL, SQL Server or Firebird do not. You need to drop the foreign keys manually in those DBMS.

How to add a foreign key referring to itself in SQL Server 2008?

I have not seen any clear, concise examples of this anywhere online.
With an existing table, how do I add a foreign key which references this table? For example:
CREATE TABLE dbo.Projects(
ProjectsID INT IDENTITY(1,1) PRIMARY KEY,
Name varchar(50)
);
How would I write a command to add a foreign key which references the same table? Can I do this in a single SQL command?
I'll show you several equivalent ways of declaring such a foreign key constraint. (This answer is intentionally repetitive to help you recognise the simple patterns for declaring constraints.)
Example: This is what we would like to end up with:
Case 1: The column holding the foreign keys already exists, but the foreign key relationship has not been declared / is not enforced yet:
In that case, run this statement:
ALTER TABLE Employee
ADD FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
Case 2: The table exists, but it does not yet have the foreign key column:
ALTER TABLE Employee
ADD ManagerId INT, -- add the column; everything else is the same as with case 1
FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
or more succinctly:
ALTER TABLE Employee
ADD ManagerId INT REFERENCES Employee (Id);
Case 3: The table does not exist yet.
CREATE TABLE Employee -- create the table; everything else is the same as with case 1
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT
);
ALTER TABLE Employee
ADD FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
or, declare the constraint inline, as part of the table creation:
CREATE TABLE Employee
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT,
FOREIGN KEY (ManagerId) REFERENCES Employee (Id)
);
or even more succinctly:
CREATE TABLE Employee
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT REFERENCES Employee (Id)
);
P.S. regarding constraint naming: Up until the previous revision of this answer, the more verbose SQL examples contained CONSTRAINT <ConstraintName> clauses for giving unique names to the foreign key constraints. After a comment by #ypercube I've decided to drop these clauses from the examples, for two reasons: Naming a constraint is an orthogonal issue to (i.e. independent from) putting the constraint in place. And having the naming out of the way allows us to focus on the the actual adding of the constraints.
In short, in order to name a constraint, precede any mention of e.g. PRIMARY KEY, REFERENCES, or FOREIGN KEY with CONSTRAINT <ConstraintName>. The way I name foreign key constraints is <TableName>_FK_<ColumnName>. I name primary key constraints in the same way, only with PK instead of FK. (Natural and other alternate keys would get the name prefix AK.)
You can add the column and constraint in one operation
ALTER TABLE dbo.Projects ADD
parentId INT NULL,
CONSTRAINT FK FOREIGN KEY(parentid) REFERENCES dbo.Projects
Optionally you could specify the PK column in brackets after the referenced table name but it is not needed here.
If the table already exists: Assuming you don't already have a column to store this data. If you do then skip this step.
ALTER TABLE [dbo].[project]
ADD [fkProjectsId] INT;
GO
ALTER TABLE [dbo].[projects]
ADD CONSTRAINT [FK_Projects_ProjectsId] FOREIGN KEY ([fkProjectsId]) REFERENCES [dbo].[Projects] ([ProjectsID])
GO

Differences between "foreign key" and "constraint foreign key"

I mean for example I can create table like
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int,
constraint fk_idq foreign key(idq) references YTable(idq)
)
and I can create it like this
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int,
foreign key(idq) references YTable(idq)
)
I usually create table like in the second example but now I'm curious about the first example. What is the difference?
The first one assigns a user-defined name to the foreign key, the second one will assign a system-generated name to the foreign key.
User-defined foreign key names can be useful for subsequent statements like these:
ALTER TABLE XTable DROP CONSTRAINT fk_idq;
ALTER TABLE XTable ENABLE CONSTRAINT fk_idq;
ALTER TABLE XTable DISABLE CONSTRAINT fk_idq;
It's harder to alter constraints with system-generated names, as you have to discover those names first.
The first option is purely for naming the constraint.
From SQL FOREIGN KEY Constraint
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
Also, from CREATE TABLE (Transact-SQL) one can see that [ CONSTRAINT constraint_name ] is optional.
Apart from controlling the name, nothing really. SQL Server will supply a name if you omit it. FYI, you only need this syntax (SQL Fiddle):
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int references YTable(idq)
)
Here's a fuller example.

Change Primary Key

I have a table in Oracle which has following schema:
City_ID Name State Country BuildTime Time
When I declared the table my primary key was both City_ID and the BuildTime, but now I want to change the primary key to three columns:
City_ID BuildTime Time
How can I change the primary key?
Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:
ALTER TABLE city
DROP CONSTRAINT pk_city;
ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);
Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.
You will need to drop and re-create the primary key like this:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.
An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):
alter table my_table drop primary key;
Sometimes when we do these steps:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
The last statement fails with
ORA-00955 "name is already used by an existing object"
Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.
You can combine the dropping of primary key constraint and unique index into a single sql statement:
alter table my_table drop constraint my_pk drop index;
check this:
ORA-00955 "name is already used by an existing object"