Wednesday, May 15, 2019

SQL Server : How to create and alter table & columns



Create table in SQL Server, firstly you need to choose right database where you want to create table.
you can change database by below query :

USE  DB_NAME;

How to create table

Create table Employee(
                                           EmployeeId integer 
                                           ,FirstName varchar(50)
                                           ,LastName varchar(50)
                                           ,DepartmentId integer
);

above Employee table doesn't have primary key, we can add primary key via above query itself
or we can add primary key constraints, see below examples :

 -- Add constraints

  Alter table Employee add constraint Emp_pk primary key (EmployeeId); 

but when you will try to execute above query you will get "Cannot define PRIMARY KEY constraint on nullable column in table 'Employee" error message. because to create primary key on a column, column should be defined as 'NOT NULL'

So, we need to alter 'Employee table's 'EmployeeId' column like:

  Alter table Employee alter column EmployeeId integer NOT NULL;

(similarly, we can change any column's attributes like( name,datatype,etc.) Now, we can run previous statement to add constraint to add primary key.

We can also mention primary key, not null, identity column declaration with create table statement.
like :

Create table Employee(
EmployeeId integer not null identity primary key
,FirstName varchar(50)
,LastName varchar(50)
,DepartmentId integer
);

We can declare NOT NULL, CHECK and UNIQUE constraints at the time of table creation same like above.

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...