SQL Server
SQL Server
SQL Server
Database
Database Table
A Database table is a tabular format and it is used to store the date of our
application , software , organization etc. Table is made of Rows and Columns.
What is SQL
What is RDBMS?
---create database
create database Student;
--use database------
use Student;
-----Create Table ---
create table MyStudents(S_id int Primary key,SName varchar(40) Not
Null,Address varchar(50),Class varchar(50),S_Age int);
------or optional---
insert into MyStudents (S_id, SName) values(11,'Raju');
-------Constraintrs----------
3) Primary key :- Combination of not null and unique. Primary key show only
one at a table can’t show again in the table.
create table MyStudents(S_id int Primary key,SName varchar(40)not
null,Address varchar(50),Class varchar(50) not null,S_Age int);
*******************************************************************
---------How to add Foreign key--------
alter table CollegeFunction add foreign key( S_id) references
MyStudents( S_id) ;
*******
create table CollegeFunction(RollNo int Primary key,SName varchar(40)
Not Null,Address varchar(50),Class varchar(50),S_Age int,S_id int
foreign key references MyStudents(S_id)on delete cascade on update
cascade);
*****************************************************************
4
6) Default :- set default value for a column when no value is given like serial
no.
create table MyStudents(S_id int Primary key,SName varchar(40) Not
Null,Address varchar(50),Class varchar(50),S_Age int default(18));
7) Index :-Use to create and retrieve data from the database very quickly.
------update row----------
update MyStudents set Address='chunabhati', Class='10th' where S_id=11
;
-----Delete Row-------
delete from MyStudents where s_id=11;
**********************************************************************************
And
**********************************************************************************
------Sql Join-----------
1) inner join
2) left join
3) Right join
4) Full Outer Join
*******************
1) inner join
********************************************************************************
***************************************************************************
------slef Join-----------
select A.SName as Student_Name,B.SName as StudentData from MyStudents
as A inner join StudentFunctions as B on A.S_id=B.S_id;
or identity(100,5)
----------Union and union All-------(Make sure column will be same two’s tables)
or
except
select * from StudentFunctions;
or
Group By Commond
The GROUP By statement is used with aggregate function
(Count,Max,Min,Sum,Avg) to group the result-set by one or more column.
We Can used one or more than one column in agroup By clause
---------Group by Count---------------(Same rows count and it’s sum)
And
10
Having Clause
Having Clause is used to specify like where Clause.
but Having clause is used with Group By Command.
We can’t use Where Clause With Group By Command.
Where Clause is used for filtering rows and having clause is
used to filtering groups.
Where Clause Does not work with aggregate function like Sum,
Min, Max, Count, Avg…
We Can use Having Clause with Aggregate Functions.
-------------------Having Clause------------
select Class, Sum(S_Age) as [Total Sum of Age Students According Address] from
MyStudents group by Class having Class in ('12th'); -----(apply on group)----
select Address, Sum(S_Age) as [Total Sum of Age Students According Address] from
MyStudents group by Address having Sum(S_Age) >= 23 ;
or ---------------Where Clause-------------
select Class, Sum(S_Age) as [Total Sum of Age Students According Address] from
MyStudents where Class in ('12th')group by Class ; ------(apply on Select
statement)---
select Address, Sum(S_Age) as [Total Sum of Age Students According Address] from
MyStudents wher eAddress in ('Borivali','Mulund','Mumbai') group by Address having
Sum(S_Age) >= 23 ;
ORDER BY KEYWORD
The order by keyword is used to sort the result-set in
ascending or descending order.
The order By keyword sorts the records in ascending
order by default.
To sort the records in descending order use the DESC
Keywords.
-------------------Order by keyword Ascending order------------
select * from MyStudents order by SName asc;
--------view in sql---------
create view vW_ForStudents as select * from MyStudents as A inner join
StudentFunctions as B on B.Myid=A.S_id;
sp_helptext vW_ForStudents111;
-----Delete view------
drop view vW_ForStudents111;
*************************************************************************************
***
12
---Like Operator------
Like operator is used in a Where Clause to searchg for a specified patter in a column
-----% operator---------
Where CustomerName LIKE ‘a%’ finds any value starts with “a”
****************
Where CustomerName LIKE ‘%a’ finds any value ends with “a”
******************
Where CustomerName LIKE ‘%or%’ finds any value have “a” in any position
*********************
Where CustomerName LIKE ‘_r%’ finds any value that have with “r” in the second
position
---------------- [] operator---------
display same letter total record like(a)
select * from MyStudents where SName Like '[a,b,c]%';
or
Sub Query
A subquery or inner query of a Nested is a query within SQL query
and embedded within the WHERE clause.
A subquery is used return data that will be used in the main
query as a condition to further restrict the data to be
retrieved.
13
-----------update subquery---------------
update MyStudents set S_Age=S_Age +10 where S_id in (select S_id from MyStudents
where S_Age = 25);
---------delete subquery----
delete from MyStudents where S_id in (select S_id from MyStudents where S_Age=35);
--oder data can't assign in subquery they can found erros but order by assign outside
subquery --------
select * from MyStudents where S_id in (select S_id from MyStudents where S_Age>20
)order by S_id;
Type O subqueries
Scalar Subquery :- subquery that return one row to the outer SQL.
14
---------in----
select * from MyStudents where S_id in (select S_id from MyStudents where
S_Age>21 );
----------any -------
select * from MyStudents where S_id < any (select S_id from MyStudents where
S_Age>21 or S_Age<25);
----all------------
select * from MyStudents where S_id < all (select S_id from MyStudents where
S_Age>21 or S_Age<26);
-Show table--
select * from StudentData_backup;
Store Procedure
A store procedure is a set of structure query language (SQL) statement with an assigned
name, which are stored in a relationship database management as group so it can be reused
and shared by multiple program.
*********************
****************
create procedure spGetStudentById @id int as begin select * from MyStudents where
S_id=@id; end
----Execute---(put on id number)
spGetStudentById 2;
-------- Store procedure with multiple parameter , changing the parameters order---
---execute ------
execute spGetStudentByIdandName 2,'Mohini';
----- Alter with stored procedure-------------
alter procedure spGetStudentByIdAndName @id int, @Name varchar(50) as begin select
SName,SAddress from MyStudents where S_id=@id and SName=@Name; end
---execute ------
execute spGetStudentByIdandName 2,'Mohini';
---execute ------
execute spGetStudentByIdAndName 2,'Mohini';
sp_helptext spGetStudentByIdandName;
----execute---
sp_helptext spGetStudentByIdandName;
Function in Programming
A Function is a Block of code that performs a specific
task.
Function usually ‘take in’ data process it and return a
results.
Once a function is written it can be used over and over
again it means function can be reused.
A function accepts input in the form of parameter and
returns a value.
SQL Server comes with a set of built-in functions that
perform a variety of tasks.
I. Scalar Functions
SQL Server scalar function takes one or more
parameters and returns a single(scalar) value.
The return value can be any data type ,except
text, ntext, image, cursor and timestamp
Scaler function can use logic such as IF blocks or
While loops.
Scaler function can’t update data. They can
access data but this is not a good practice.
Scaler function call the other functions.
------show function---
select dbo.TakeNumber(2);
-------Create function with Multiple parameter---
create function Addition(@num1 as int ,@num2 as int) returns int as begin
return(@num1+@num2) end;
--show function---
select dbo.Addition(5,6);
---reused function---
select dbo.Addition(23,34);
19
select dbo.CheckVoterAge(20);
select dbo.CheckVoterAge(16);
-----show function---
select dbo.GetMyDate();
1. Multi -Statement
o A multi Statement table-valued function is a table-
valued function that returns the result of multiple
statements.
o The multi-statement-valued function is very useful
because you can execute multiple queries within the
function and aggregate result into the returned
table.
o To defined a multi-statement table-valued function
you used a table variable as the return value. Inside
the function you execute one or more queries and
insert data into this table variable
or
In this there are no BEGIN and END In this we have to use BEGIN and
Blocks END blocks.
Inline table-valued function are Ther is no performance advantages
better in performance as compared in multi statement table-valued
to multi statement table valued functions.
functions.
Similaries
---------------------table3-----------
create table StudentFunctions222(F_RollNo int ,SName varchar(40) Not Null,Address
varchar(50),Class varchar(50), S_id int);
Trigger
A trigger is a special kind of stored procedure that automatically execute when an
event occurs in the database server.
There are three types of triggers
DML triggers (Data Manipulation language) Insert,Update ,Delete
DDL Triggers (Data Definition Language) Create ,Alter
Logon Triggers
-show table-
select * from MyStudents;
---show table-
select * from MyStudents;
---show table-
select * from MyStudents;
----DDL isert one table to another table automatically inserted values ---------
create trigger tr__StudentsAuditInsert on MyStudents after insert as
begin
Declare @id int
select @id=S_id from inserted
---------show otput------------
********************************
------another table---------
25
----DDL delete one table row to another table automaticalyy deleted values print
---------
create trigger tr__StudentsAuditDelete on MyStudents after delete as
begin
Declare @id int
select @id=S_id from deleted
insert into Students_Audit
values('Existing Student with id'+ Cast (@id as varchar(50)) + ' is deleted at' +
Cast(GetDate() as varchar(50)));
end
*****************************************
----DDL update one table row to another table automaticalyy update and delete values
print ---------
create trigger tr__StudentsAuditUpdated on MyStudents after update as
begin
select * from inserted
select * from deleted
end
*****************************************************************************************
2.Instead triggers
Instead of triggers is executed in place of the insert ,update, or delete
operators
We can view the definition triggers by using sp_helptext system stored procedure.
We can use Alter (create) Statement with Triggers.
Modifying DML triggers by using Drop and Recreate or Alter trigger statement.
26
A DML Trigger can be Encrypted to HIDE its Definition or Query By Using With
Encryption command.
----show table---
select * from MyStudents;
for insert
--------Insted of insert trigger-----
create trigger tr_CustomerIntedTr on MyStudents
instead of insert as
begin
print 'you are not allow insert data in this table !!'
end
--update row---
update MyStudents set SName='sudhakar matre' ,S_Age=44 where S_id=6;
--delete row---
delete from MyStudents where S_id=5;
****************************************************
Insert table one to another table
---drop trigger------
drop trigger tr_CustomerIntedTr;
---inser row---
insert into MyStudents values(8,'Komal','Dadar','15th',24);
----show table data---
select * from CustomerAudit;
***********************************************
for Update
-----create another table----------------
create table CustomerAudit(Audit_id int primary key identity , Audit_information
varchar(max));
---drop trigger------
drop trigger [tr_CustomerIntedUpdate];
---update data-
create trigger tr_CustomerAuditUpdate on MyStudents
instead of update as
begin
insert into CustomerAudit values('Some one tries to updatet data in customer table at:'+
Cast(GETDATE() as varchar(50)));
end
For delete
---drop trigger------
drop trigger [tr_CustomerIntedDelete] ;
---delete data----
create trigger tr_CustomerAuditDelete on MyStudents
instead of delete as
begin
insert into CustomerAudit values('Some one tries to delete data in customer table at:'+
Cast(GETDATE() as varchar(50)));
end
We can view the definition of trigger but using sp_helptext system stored
procedure.
---view trigger---
sp_helptext tr_CustomerAuditDelete;
**************************************************
Encryption and decryption trigger
-----create another table----------------
create table CustomerAudit(Audit_id int primary key identity , Audit_information
varchar(max));
---drop trigger------
drop trigger [tr_CustomerAuditDelete] ;
---encripyted data----
create trigger tr_CustomerAuditDeleteEncryption on MyStudents with encryption
instead of delete as
begin
insert into CustomerAudit values('Some one tries to delete data in customer table at:'+
Cast(GETDATE() as varchar(50)));
end
---view trigger---
sp_helptext [tr__StudentsAuditUpdated];
-------with descripted-------
alter trigger tr_CustomerAuditDeleteEncryption on MyStudents
instead of delete as
begin
insert into CustomerAudit values('Some one tries to delete data in customer table at:'+
Cast(GETDATE() as varchar(50)));
end
---view trigger---
sp_helptext [tr__StudentsAuditUpdated]
;
29
----show table---
select * from MyStudents;
----instead of trigger----------
create trigger tr_insteadOfTrigger on vw_StudentsDetail
instead of delete as
begin
delete from MyStudents where S_id in
(select S_id from deleted)
delete from StudentFunctions where S_id in
(select S_id from deleted)
end
*****************************************************************************************
DDL Triggers
DDL (Data Definition language) triggers execute stored procedures when DDL
events such as CREATE,ALTER and DROP statement occurs in the database or
server.
----show table---
select * from MyStudents;
----alter trigger---
alter trigger tr_DDLCreatetable on database for ALTER_TABLE as
begin
31
***************
sp_helptext tr_ddl_sp_Creat;
---disabled trigger-------
disable trigger tr_ddl_sp_Create on database;
---------rename procedure--------
create trigger tr_ddl_REname on database for RENAME as
32
begin
print ' you have just rename table column ';
end
sp_rename 'Test2','Test4';
We can also use with encryption command with server scoped DDL
triggers.
We can also Enable And Disable Trigger ON server Scope DDL Triggers.
-----drop trigger----
drop trigger [tr_MyDatabaseTrigger] on database;
---disabled trigger
disable trigger [tr_MyServerScopeTrigger] on All server;
---enabled trigger
enable trigger [tr_MyServerScopeTrigger] on All server;
--------show trigger----------
create table Server_table2(id int);
*********************************************************************
Execution order of DML Triggers
Sql server 2012 allows users to specify which AFTER trigger is to be
executed first and which is to be executed last.
SP_SetTriggersOrder
@Triggername :-is the name of the DML or DDL trigger and the
schema to which it belongs and whose order needs to be
specified.
@Order :specified the execution order of the trigger as
FIRST ,LAST or NONE . if First is specified then trigger is fired
first
@StmtType(Statement type):specified the type of SQL statement
(Insert, Update, Delete)that invoke the DML trigger.
execute sp_settriggerorder
@triggername ='tr_MyDatabaseTrigger1',
@order ='first',
@stmttype = 'insert';
execute sp_settriggerorder
@triggername ='tr_MyDatabaseTrigger3',
@order ='last',
@stmttype = 'insert';
*********************************************
GUID(globaly Unique Identifire) note this is used for big data sizing
Advantages
A guid is unique across tables, database and servers.
Usefull if you are consulting records from multiple SQL server into a
single table
DisAdvantages
select newid();
select * from Customer2;
NORMALIZATION
Database Normalization is the process of organizing data to minimize
data redundancy (data duplication)which lea to data inconsistency.
Data normalization is the step by step process. There are 6 Normal
Forms.
Does not contain column (Attribute ) that are not fully dependent
on the Primary key.
If an attribute can be deteremind by another Non-key attribute it
is called a transitive dependency.
To make it simpler every non-key attribute should be determined
by the key attribute only.
If a Non -key attribute can be determinded by another non-key
attribute it needs to put into another table.
***********************************************************************
String Functions
Ascii() :-Returns the ASCII code of the given character.
select ascii('A');
select ascii('Z');
select ascii('a');
select char(65);
LTRIM() :-Removes blank on the left hand side of the given character
expression.
RTRIM() :- Removes blank on the right hand side of the given character
expression.
select 'hello ';
LEN() :-Returns the count (int) of total character int a string excluding the
blanks at the end of the expression.
*****************************************************************************************
INDEXES
On the other hand if you have the index in a book you lookup
the page number of the character in the index and then
directly go the that page number to locate the character .
sp_helpindex MyStudents;
CLUSTER INDEX
NON-CLUSTER INDEX
40
sp_helpindex MyStudents;
**************************************************************
Computed Columns
***************************************************************************************
-----------cube----------
select Address,Gender, sum(Salary) as Total_Salary from EmlpoyyesDB group by
cube(Address,Gender);
************************************
ROLLUP
In additions to the usual rows that are generated by the GROUP BY
clause , it also introduced summary rows into the result set.
It arrange the groups from the lowest to the highest.
It is similar to CUBE operator but generates a result set that shows
groups arranged in a hierarchical order.
Group hierarchy in the result is dependent on the order in which the
columns that are grouped are specified.
or
select Address,Gender, sum(Salary) as Total_Salary from EmlpoyyesDB group by
rollup(Address,Gender);
Grouping set
The grouping set operator allows us to you group together multiple
grouping of columns followed by an optional grand total row denoted by
parentheses().
or
select Address,Gender, sum(Salary) as Total_Salary from EmlpoyyesDB group by grouping
sets(( Address,Gender),(Address),(Gender),()) order by grouping
(Address),grouping(Gender);
Marge Statements
The marge statement introduced in sql server 2008.
The marge Statement allows us to perform insert, updates and delete in
one statement. This means we have no longer have to use multiple
statement to perform insert, update ,delete.
The merge statement allow you to maintain a target based on certain
join conditions on a source table using a single statement.
With merge statement we required 2 tables
1. Source Table: Contains the charges that need to be applied to
the target table.
2. Target Table: The table that required changes (insert , Update
and Delete)
Merge statement joins the target table to the source table by using a
command column in both the tables. Base on the how the rows match up
we can perform insert, update and delete on the target table.
You can now perform the following actions in the Merge statement :
i. Insert a new row from the source if the row is missing in the
target table.
ii. Update a target row if a record already exist in the source
table.
43
iii. Delete a target row if the row is missing in the source table .
merge MyStudents as T
using EmlpoyyesDB as S
on T.id=S.id
when matched then
update set T.Name=S.Name, T.Address=S.Address
when not matched by target then
insert(id,name,address)values(S.id,S.Name,S.Address)
when not matched by source then Delete;
----------show table------------
select * from EmlpoyyesDB;
select * from MyStudents;
*****************************************************************************
Transaction
A Transaction is
o A single until of work .
44
Defination of transactions
A logical unit of work must exhibit four properties called the
atomicity consistency ,isolation and durability (ACID) properties to
qualify as a transaction.
********************************************************************
TRY CATCH
o Implements error handline for transact-SQL that is similar to the
exception handling in the Microsoft visual c# and java languages.
o In TRY block when error occur on the line then after that line no
lines will be executed.
begin try
select 10/0
select * from MyStudents;
end try
begin catch
print 'You canot divided a number by zero '
end catch
begin try
update MyStudents set SName='shital' where s_id=3
46
end try
begin catch
print 'You canot insert string value '
end catch
These functions return NULL if they called outside the scope of the
CATCH block.Error information can be retrieved by using these
functions from anywhere within the scope of CATCH block.
begin try
update MyStudents set SName='abc' where s_id=3
end try
begin catch
select
ERROR_NUMBER() as [Error Number],
ERROR_SEVERITY() as [Error Severity],
ERROR_STATE() as [Error State Number],
ERROR_PROCEDURE() as [SP Name],
ERROR_LINE() as [Error Line],
ERROR_MESSAGE() as [Error Message]
end catch
**********************************************************************
begin transaction
insert into MyStudents values(7,'Suhana','KanjurMarg','12th',21)
insert into MyStudents values(8,'Shobhana','dadar','12th',21)
commit transaction
print 'Transaction sucefully done';
end try
begin catch
rollback transaction
print 'Tranaction fail';
select ERROR_MESSAGE() as [Error Message]
end catch
***************************************************************************************
TEMPORARY TABLE
Temporary tables are very similar t the permanent tables .
A temporary tables in SQL server as the name suggest is a database table that
exist temporarily on the database server.
Temporary table are created in TempDb.
Temporary resides in system database in SSMS.
Temporary tables are very useful when we need to store temporary data.
Two types of temporary table
i. Local temporary tables
ii. Global temporary tables
end
execute spEMPData;
*****************************************************************
COALESCE() FUNCTION
Return the first non-null value in a list.
CAST() FUNCTION
The cast() function convert a value (of any type) into a
specified datatype.
select cast(23.34 as int )as value;
select cast('2021-05-04' as datetime);
*****************************************************************************************
CONVERT() FUNCTION
Convert() function converts a value (of any datatype) into a
specified datatype.
-----same datatype----------
select cast(23.34 as int )as value;
select convert( int ,23.34 )as value;
-----declare datatype----------
declare @num1 decimal=24.5;
select cast(@num1 as int );
select @num1;
---datetime convert-----
select cast('2021-05-04' as datetime);
select convert( datetime,'2021-05-04');
----current datetime-----
select getdate();
select convert(varchar,getdate());
select convert(varchar,getdate(),0);
select convert(varchar,getdate(),1);
select convert(varchar,getdate(),101);
50
*****************************************************************************************
CURSOR
Cursor is a temporary memory or temporary work station.
A SQL cursor is a database object that is used to retrieved data
from a result set one row at a time.
It is allocated by database server at the time of performing DML
operation on table by user.
Cursor are used to store Database tables.
It allows you to process individual row returned by query.
Type of cursors
i. Implicit cursor
Implicit cursor are also known as default cursor of
sql server.
These cursor are allocated by sql server when the user
performs DML operations.
Methods of cursors
Next
Prior
First
Last
Absolute n
Relative n
B. Opening cursor
A cursor is opened for storing data retrieved from
the result set.
open myCursors
C. Fetching cursor
51
D. Closing cursor
The cursor should be closed explicitly after data
manipulation.
close myCursors
E. De-allocating cursor
Cursor should be deallocated to delete cursor
definition and release all the system resource
associated with the cursor.
deallocate myCursors;
------with cursor--------------
declare myCursors cursor scroll for select * from MyStudents
open myCursors
fetch first from myCursors
fetch next from myCursors
fetch last from myCursors
fetch prior from myCursors
fetch absolute 4 from myCursors
fetch relative 3 from myCursors
fetch relative -1 from myCursors
close myCursors
deallocate myCursors;
------with cursor--------------
declare myCursors cursor scroll for select S_id,SName from MyStudents
declare @Std_id int, @Std_Name varchar(50)
open myCursors
fetch first from myCursors into @Std_id ,@Std_Name
print'Student is :' + cast(@Std_id as varchar(50))+' ' +@Std_Name
The difference is With GROUP BY you can only have the aggregate
values for the column that are not include in GROUP By.
create table Employee(id int ,Name varchar(50), Gender varchar(50), salary int,Age int);
---subquery---(--inner join--)
select name,salary ,Employee.gender ,genders.Gender_Total from Employee
inner join
(select gender,count(*) as Gender_Total from Employee group by gender)as genders
on Employee.gender=genders.gender;
----over clause----
select name,gender,salary,count(gender) over (partition by gender)as Gendet_Total from
Employee;
---Min/Max/Average--------------
select gender,count(*) as Gender_Total,
Max(salary) as Max_salary ,
Min(salary) as Min_Salary,
avg(salary) as Avg_SAlary
from Employee group by gender;
-----partition by--------
select name,gender,salary,
count(gender) over (partition by gender) as Gender_Total,
Max(Salary) over (partition by gender) as Max_Salary,
Min(Salary) over (partition by gender) as Min_salary,
Avg(Salary) over (partition by gender) as Avg_Salary
from Employee;
**********************************************************************
RETRIVING LAST GENERATED IDENTITY VALUE
create table Employee(id int ,Name varchar(50), Gender varchar(50), salary int,Age int);
select SCOPE_IDENTITY();
select @@IDENTITY;
*********************************************************************
Row_Number function
----partition by gender---------
select *, ROW_NUMBER() over(partition by gender order by name desc) as Numbering from
Employee;
---partition by Age-----
select *, ROW_NUMBER() over(partition by Age order by name desc) as Numbering from
Employee;
***************************************************************
**********************************************************************
CROSS APPLY & OUTER APPLY
56
A. Cross Apply
B. Outer Apply
---inner join------
select * from MyStudents inner join StudentFunctions on
MyStudents.S_id=StudentFunctions.t_id;
---left join----
select s.SName,s.Class,t.SName,t.Address
from MyStudents as s
left join StudentFunctions as t
on s.S_id=t.t_id;
****************************************************************
CTE (Common Table Expression)
CTE stands for common table expression
CTE is introduced in SQL Server-2005.
A CTE allow you to defined a temporary result set that can be
linked immediately with the select, insert, update or delete
statement.
CTE is similar to a temporary resultset defined within the
execution scope of the single SELECT, INSERT, UPDATE, DELETE or
CREATE VIEW statement.
The CTE can also used in the view
A CTE is defined at the start of a query and can be referenced
several times in the outer query.
Key advantages Of CTEs are improved readability and ease in
maintenance of complex queries.
Syntax: With expression_name(Column1, column2,…)
As ( CTE_definition )
CTE exist in memory only while the query is running .After the
query is run CET is discarded it can’t be used for the next SQL
query unless we defined it against .Still the same CTE might be
reference several times in the main query and any subqueries.
A view is a stored SQL query that is execute each time you
reference it in another query .Note that a view doesn’t store the
output of a particular query -it stores the query itself.
The key thing to remember about SQL view is that in contrast to a
CTE a view is a physical object in database and is stored on a
disk .However views store the query only not the data returned by
the query .The data is computed each time you reference the view
in your query.
59
create table Employee(id int ,Name varchar(50), Gender varchar(50), salary int,Age int);
---column of CTE---
with New_CTE(E_id,E_Name,E_salary) as (select id,Name,salary from Employee where
Gender='Male')
select E_id,E_Name from New_CTE
---create view-----
create view vWMyNewView
as
with New_CTE as (select * from Employee where Age>=25)
select * from New_CTE
select Current_TimeStamp;
----------------------END-----------------------------