Sql Server Create,Alter ,Drop Primary Keys Constraint|Find the constraint

Primary key Constraints.

1. Primary keys must contain UNIQUE values

2. A primary key column cannot contain NULL values.

3. Each table can have only ONE primary key.

Create Primary key Constraints.
SQL/MYSQL
CREATE TABLE Employee
(
Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
CityCode varchar(255),
CONSTRAINT PK1 PRIMARY KEY (Id)
)

PrimaryKey Combined two columns.
SQL/MYSQL
CREATE TABLE Employee
(
Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
CityCode varchar(255),
CONSTRAINT PK1 PRIMARY KEY (Id,CityCode)
)

Select Primary Key.
SQL 
select OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
where OBJECT_NAME(parent_object_id)='Employee'
and type_desc LIKE '%CONSTRAINT'

Result:
Mysql 
SELECT k.`COLUMN_NAME`
FROM `information_schema`.`TABLE_CONSTRAINTS` t
JOIN `information_schema`.`KEY_COLUMN_USAGE` k
USING (`CONSTRAINT_NAME`, `TABLE_SCHEMA`, `TABLE_NAME`)
WHERE t.`CONSTRAINT_TYPE` = 'PRIMARY KEY'
AND t.`TABLE_SCHEMA` = 'demo'
AND t.`TABLE_NAME` = 'employee';
Drop primary key.
SQL 
ALTER TABLE Employee
DROP CONSTRAINT PK1
MYSQL
ALTER TABLE employee DROP PRIMARY KEY

Result:
Add Primary Key.
SQL/MYSQL
alter table Employee add CONSTRAINT PK1 primary key (ID)
Result:

Post a Comment

0 Comments