Need help in updating primary key field - sql

create table school_student(
id int not null,
name varchar(20),
DOB Date,
Address varchar(50),
phone_no int,
primary key(id)
);
need to update the primary key column to auto increment in sql
alter table school_student alter column id int not null identity(5,1) primary key
i am getting below error,
Incorrect syntax near the keyword 'identity'.

Thanks Mayur Sawant for your reply from other post :) Its helped to drop the primary and foreign key .
Reference to his post :
Usage of Alter command to drop Primary key and Foreign Key
First of all you need to find the constraint name related to the Primary and Foreign keys. Then you need to use these constraint names while dropping the keys.
select *
from
information_schema.key_column_usage
where
table_name = 'my_table'
From the above query you will be able to find the constraint names.
Now use the below syntax to drop the keys.
ALTER TABLE tablename DROP CONSTRAINT constraint name

Related

Can't add foreign key constraint to table

CREATE TABLE CUSTOMER
(
CNUM VARCHAR(25) NOT NULL,
CNAME VARCHAR(75) NOT NULL,
CTYPE VARCHAR(20) NOT NULL,
CONSTRAINT CUSTOMER_PK PRIMARY KEY(CNUM),
CONSTRAINT CHECK_CTYPE CHECK(CTYPE IN('INDIVIDUAL', 'INSTITUTION'))
);
CREATE TABLE CREDIT_TERM
(
CREDITSTATUS VARCHAR(20) NOT NULL,
STARTDATE DATE NOT NULL,
ENDDATE DATE NOT NULL,
CONSTRAINT CREDIT_TERM_PK PRIMARY KEY(CREDITSTATUS)
);
insert into CREDIT_TERM values('ONE-MONTH','15-05-2015','15-06-2015');
insert into CREDIT_TERM values('TWO-MONTH','15-05-2015','15-06-2015');
insert into CREDIT_TERM values('THREE-MONTH','15-05-2015','15-06-2015');
ALTER TABLE CUSTOMER
ADD CONSTRAINT CUSTOMER_FK_CREDITSTATUS
FOREIGN KEY(CREDITSTATUS) REFERENCES CREDIT_TERM(CREDITSTATUS);
I am trying to add a foreign key constraint, but I don't understand why I get this error:
ERROR at last line :
ORA-00904: "CREDITSTATUS": invalid identifier
As I noted in the comments, your customer table does not have a creditstatus column. You'd first have to add it:
ALTER TABLE customer ADD creditstatus VARCHAR2(20);
And then make it a foreign key, with the statement you already have.
You're trying to add a foreign key constraint for a foreign key named CREDITSTATUS on the CUSTOMER table. However, the CUSTOMER table doesn't have a foreign key for CREDITSTATUS.
You'll have to create a foreign key in CUSTOMER for CREDITSTATUS, then rerun the last line to add the constraint.
EDIT
Use ALTER TABLE to add the column to CUSTOMER:
ALTER TABLE CUSTOMER ADD CREDITSTATUS VARCHAR(20);
Docs:
http://www.techonthenet.com/oracle/tables/alter_table.php
You can add the column and the foreign key constraint in one statement:
alter table customer add (
creditstatus varchar2(20) constraint customer_fk_creditstatus references credit_term
);
A few notes. First, I enclosed the column definition in parentheses. It may work without them, but the official syntax seems to require them. http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_3001.htm#i2103924
Second, in an in-line constraint (defined at the column level, not at the table level), you may not use the words FOREIGN KEY. The word REFERENCES already identifies the constraint type. Third, if you reference the PRIMARY KEY of the referenced table, you are not required to (but you may if you wish) name the referenced column in the referenced table. If you don't name the column, the PRIMARY KEY of the referenced table will be used by default - which is what you want anyway, in the vast majority of cases.

Adding constraints on table

I am new to SQL Oracle.I have the following script:
create table students(
sid char(10),
honors char(10) not null,
primary key (sid),
Constraint studentConst foreign key (honors) references Courses(cid),
);
create table Courses(
cid char(10),
grader char(20) not null,
primary key (cid),
Constraint CoursesConst foreign key (grader) references students(sid),
);
SET CONSTRAINT studentConst,CoursesConst DEFERRED;
I get the following error on running the above script:
SQL Error: ORA-00904: : invalid identifier on line 5. Why do I get this error ?
I don't think you can create a foreign key constraint on a table that doesn't yet exist.
Since you have a two-way constraint, you'll need to create the first table without the constraint, then add it with alter table after the second table has been created.
Deferred constraints are for checking data. Deferral simply means the check won't be carried out until the end of the transaction. It does not mean "defer the creation of the constraints so I can set up a circular reference" :-)
It looks like line 5 is trying to reference Courses(cid). However, at this point, the Courses table does not exist, as it's created in the following SQL block.
Try creating dependent tables first.
Add the constraint after the tables are built. You can do this using an alter table statement:
create table students(
sid char(10),
honors char(10) not null,
primary key (sid)
);
create table Courses(
cid char(10),
grader char(20) not null,
primary key (cid),
Constraint CoursesConst foreign key (grader) references students(sid)
);
alter table students add constraint studentConst foreign key (honors) references Courses(cid)
The SQLFiddle is here.

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"

How do I create a foreign key in SQL Server?

I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far:
drop table exams;
drop table question_bank;
drop table anwser_bank;
create table exams
(
exam_id uniqueidentifier primary key,
exam_name varchar(50),
);
create table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint question_exam_id foreign key references exams(exam_id)
);
create table anwser_bank
(
anwser_id uniqueidentifier primary key,
anwser_question_id uniqueidentifier,
anwser_text varchar(1024),
anwser_is_correct bit
);
When I run the query I get this error:
Msg 8139, Level 16, State 0, Line 9
Number of referencing columns in
foreign key differs from number of
referenced columns, table
'question_bank'.
Can you spot the error?
And if you just want to create the constraint on its own, you can use ALTER TABLE
alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn)
I wouldn't recommend the syntax mentioned by Sara Chipps for inline creation, just because I would rather name my own constraints.
create table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)
);
You can also name your foreign key constraint by using:
CONSTRAINT your_name_here FOREIGN KEY (question_exam_id) REFERENCES EXAMS (exam_id)
I like AlexCuse's answer, but something you should pay attention to whenever you add a foreign key constraint is how you want updates to the referenced column in a row of the referenced table to be treated, and especially how you want deletes of rows in the referenced table to be treated.
If a constraint is created like this:
alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn )
references MyOtherTable(PKColumn)
.. then updates or deletes in the referenced table will blow up with an error if there is a corresponding row in the referencing table.
That might be the behaviour you want, but in my experience, it much more commonly isn't.
If you instead create it like this:
alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn )
references MyOtherTable(PKColumn)
on update cascade
on delete cascade
..then updates and deletes in the parent table will result in updates and deletes of the corresponding rows in the referencing table.
(I'm not suggesting that the default should be changed, the default errs on the side of caution, which is good. I'm just saying it's something that a person who is creating constaints should always pay attention to.)
This can be done, by the way, when creating a table, like this:
create table ProductCategories (
Id int identity primary key,
ProductId int references Products(Id)
on update cascade on delete cascade
CategoryId int references Categories(Id)
on update cascade on delete cascade
)
create table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null constraint fk_exam_id foreign key references exams(exam_id),
question_text varchar(1024) not null,
question_point_value decimal
);
--That will work too. Pehaps a bit more intuitive construct?
To Create a foreign key on any table
ALTER TABLE [SCHEMA].[TABLENAME] ADD FOREIGN KEY (COLUMNNAME) REFERENCES [TABLENAME](COLUMNNAME)
EXAMPLE
ALTER TABLE [dbo].[UserMaster] ADD FOREIGN KEY (City_Id) REFERENCES [dbo].[CityMaster](City_Id)
If you want to create two table's columns into a relationship by using a query try the following:
Alter table Foreign_Key_Table_name add constraint
Foreign_Key_Table_name_Columnname_FK
Foreign Key (Column_name) references
Another_Table_name(Another_Table_Column_name)
Like you, I don't usually create foreign keys by hand, but if for some reason I need the script to do so I usually create it using ms sql server management studio and before saving then changes, I select Table Designer | Generate Change Script
This script is about creating tables with foreign key and I added referential integrity constraint sql-server.
create table exams
(
exam_id int primary key,
exam_name varchar(50),
);
create table question_bank
(
question_id int primary key,
question_exam_id int not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint question_exam_id_fk
foreign key references exams(exam_id)
ON DELETE CASCADE
);
Necromancing.
Actually, doing this correctly is a little bit trickier.
You first need to check if the primary-key exists for the column you want to set your foreign key to reference to.
In this example, a foreign key on table T_ZO_SYS_Language_Forms is created, referencing dbo.T_SYS_Language_Forms.LANG_UID
-- First, chech if the table exists...
IF 0 < (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
-- Check for NULL values in the primary-key column
IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
BEGIN
ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL
-- No, don't drop, FK references might already exist...
-- Drop PK if exists
-- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name
--DECLARE #pkDropCommand nvarchar(1000)
--SET #pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
--WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
--AND TABLE_SCHEMA = 'dbo'
--AND TABLE_NAME = 'T_SYS_Language_Forms'
----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
--))
---- PRINT #pkDropCommand
--EXECUTE(#pkDropCommand)
-- Instead do
-- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';
-- Check if they keys are unique (it is very possible they might not be)
IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
BEGIN
-- If no Primary key for this table
IF 0 =
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
-- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
)
ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
;
-- Adding foreign key
IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms')
ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID);
END -- End uniqueness check
ELSE
PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...'
END -- End NULL check
ELSE
PRINT 'FSCK, need to figure out how to update NULL value(s)...'
END
I always use this syntax to create the foreign key constraint between 2 tables
Alter Table ForeignKeyTable
Add constraint `ForeignKeyTable_ForeignKeyColumn_FK`
`Foreign key (ForeignKeyColumn)` references `PrimaryKeyTable (PrimaryKeyColumn)`
i.e.
Alter Table tblEmployee
Add constraint tblEmployee_DepartmentID_FK
foreign key (DepartmentID) references tblDepartment (ID)