Delete constraint and table - sql-server

I created table named as Dates and also I inserted value from other table. You can see how look lines of code below
--Create table
CREATE TABLE [dimension].[Dates](
[Year] [int] NOT NULL,
[Month] [tinyint] NOT NULL,
[MonthName] [varchar](10) NOT NULL,
[Quarter] [tinyint] NOT NULL,
[MMYYYY] [char](6) NOT NULL
CONSTRAINT [PK_Dates] PRIMARY KEY CLUSTERED (MMYYYY ASC))
--Insert data
INSERT INTO [dimension].[Dates] ([Year],[Month],[MonthName],[MonthName], [MMYYYY])
SELECT DISTINCT [Year],[Month],[MonthName]0,[MonthName], [MMYYYY]
FROM [dimension].[Date]
Additionally I assign foreign key on FACT.FactTable with primary key of this table with this line of code.
ALTER TABLE FACT.FactTable
ADD
FOREIGN KEY (MMYYYY) REFERENCES [DIMENSION].[Dates] (MMYYYY)
So far so good. But know I want to delete this table and make again with additional columns. In order to do this I use this command below but can't work.
ALTER TABLE DIMENSION.Dates
DROP CONSTRAINT [PK_Dates]
Msg 3725, Level 16, State 0, Line 183
The constraint 'PK_Dates' is being referenced by table 'FactTable', foreign key constraint 'FK__FactTable__MMYYY__33F4B129'.
Msg 3727, Level 16, State 0, Line 183
Could not drop constraint. See previous errors.
Because this line don't work for me I can use command drop table to delete this table, so can anybody help me how to solve this issue?

You cannot DROP table if there are other tables that are referencing to your dimension.Dates table or in other case you cannot DELETE data if there are other tables which data are referenced to data in table FACT.FactTable. You should first drop CONSTRAINT and then drop table.
ALTER TABLE FACT.FactTable DROP CONSTRAINT FK__FactTable__MMYYY__33F4B129;
Once the constraint is dropped and you don't have any other references to dimention.Dates you can execute the following statement:
DROP TABLE dimension.Dates;

The error message says the FACT.FactTable's foreign depends on PK_Dates. Drop that first. It doesn't look like you can modify it from a quick reading of the documentation.

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.

Unable to add a constraint foreign key to a table from an already created table in SQL server management studio 18. Can someone help me?

I'm creating a database for my assignment. I had to create 2 tables namely Customer and Job through the "New Query" option in SQL server. After creating both of them, I wanted to add Job_ID (A primary key) from Job table as a foreign key to the Customer table. As I have already created the Customer table, The only option I had was to ALTER the customer table. But after altering, I seemed to get this unusual error.
Msg 1769, Level 16, State 1, Line 1
Foreign key 'Job_ID' references invalid column 'Job_ID' in referencing table 'CUSTOMER'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint or index. See previous errors.
I can provide you with any more info if necessary.
CREATE TABLE CUSTOMER
(Customer_ID INT NOT NULL PRIMARY KEY,
Customer_Name VARCHAR(15) NOT NULL,
Gender CHAR(1),
Customer_Type VARCHAR(12) NOT NULL,
Addresss VARCHAR(20) NOT NULL,
Telephone_No CHAR(10) NOT NULL);
CREATE TABLE JOB
(Job_ID INT NOT NULL PRIMARY KEY,
Pickup_location VARCHAR (10) NOT NULL,
Destination VARCHAR (10) NOT NULL,
Customer_ID INT FOREIGN KEY REFERENCES CUSTOMER(Customer_ID));
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (Job_ID) REFERENCES JOB(Job_ID);
This looks like the same issue as described here.
When you try to create your foreign key:
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (Job_ID) REFERENCES JOB(Job_ID);
You are saying that you want to use the field Job_ID from the table CUSTOMER:
ALTER TABLE CUSTOMER ADD FOREIGN KEY (Job_ID)
and that the values in this field should match values in the Job_ID column from the table JOB:
REFERENCES JOB(Job_ID);
The problem is that your CUSTOMER table doesn't have a Job_ID column, based on its definition:
CREATE TABLE CUSTOMER
(Customer_ID INT NOT NULL PRIMARY KEY,
Customer_Name VARCHAR(15) NOT NULL,
Gender CHAR(1),
Customer_Type VARCHAR(12) NOT NULL,
Addresss VARCHAR(20) NOT NULL,
Telephone_No CHAR(10) NOT NULL);
The fields in the CUSTOMER table are Customer_ID,Customer_Name,Gender,Customer_Type,Addresss and Telephone_No.
So you either need to add a Job_ID column to the CUSTOMER table, or specify a different field to use in your ALTER TABLE statement - one which does exist in the CUSTOMER table.
More information on ALTER TABLE and ADD FOREIGN KEY specifically can be found here.

Error upon creating tables in sqlplus

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.

New uniqueidentifier on the go

I want to add a column for a table which would become a PRIMARY KEY and be of type uniqueidentifier. I have this, but I wonder if there is a faster (in fewer code lines) way?
ALTER TABLE [table] ADD [id] [uniqueidentifier]
DEFAULT('00000000-0000-0000-0000-000000000000') NOT NULL
GO
UPDATE [table] SET [id] = NEWID()
GO
ALTER TABLE [table] ADD CONSTRAINT [PK_table_id] PRIMARY KEY CLUSTERED
GO
If you want to keep naming your constraints (and you should), I don't think we can reduce it below 2 statements:
create table T (
Col1 varchar(10) not null
)
go
insert into T (Col1)
values ('abc'),('def')
go
ALTER TABLE T ADD [id] [uniqueidentifier] constraint DF_T_id DEFAULT(NEWID()) NOT NULL
GO
ALTER TABLE T ADD constraint PK_T PRIMARY KEY CLUSTERED (id)
go
drop table T
Note, that I've added a name for the default constraint. Also, this ensures that new rows also have id values assigned. As I said in my comment, it's usually preferable to avoid having columns with values generated by NEWID() clustered - it leads to lots of fragmentation. If you want to avoid that, consider NEWSEQUENTIALID().
If you don't care about constraint names, you can do it as a single query:
ALTER TABLE T ADD [id] [uniqueidentifier] DEFAULT(NEWID()) NOT NULL PRIMARY KEY CLUSTERED

SQL Server 2008 - Create a Join Table

I'm having issues creating a simple join table (associative table, etc. whatever your flavor is).
These are test tables, so there is not much to them.
First table is
CREATE TABLE dbo.CareerField(
CareerFieldID int IDENTITY(1,1) NOT NULL,
CareerFieldName varchar(100) NOT NULL
)
Second Table is
CREATE TABLE dbo.Cluster(
ClusterID int IDENTITY(1,1) NOT NULL,
ClusterName varchar(100) NOT NULL
)
Third table (join table) to create a many-to-many relationship is
CREATE TABLE dbo.CareerField_Cluster(
CareerFieldID int NOT NULL,
ClusterID int NOT NULL
)
I am trying to set foreign keys in this third table using the following
ALTER TABLE dbo.CareerField_Cluster
ADD CONSTRAINT FK_CareerField_Cluster_CareerFieldID
FOREIGN KEY(CareerFieldID) REFERENCES dbo.CareerField(CareerFieldID)
ALTER TABLE dbo.CareerField_Cluster
ADD CONSTRAINT FK_CareerField_Cluster_ClusterID
FOREIGN KEY(ClusterID) REFERENCES dbo.Cluster(ClusterID)
However, I keep getting an error of
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'dbo.CareerField' that match the referencing column list in the foreign key 'FK_CareerField_Cluster_CareerFieldID'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
I try setting both fields as a primary key, but it will not allow me to select a separate table when creating the key - I can't select CareerFieldID to reference CareerField Table and then ClusterID to reference Cluster Table.
I've not had this issue with MySQL and I am new to SQL Server. Any help is much appreciated.
For each of your tables CareerField and Cluster, ensure you have a PK designated via the CONSTRAINT directive.
CREATE TABLE [dbo].[CareerField]
(
[CareerFieldID] [int] IDENTITY(1,1) NOT NULL,
[CareerFieldName] [varchar](100) NOT NULL,
CONSTRAINT [PK_Career] PRIMARY KEY CLUSTERED
(
[CareerFieldID] ASC
)
)

Resources