You are on page 1of 17

Print A to Z

Select char(65)

Declare @start int


Set @start=65
While (@start<=90)
Begin
Print char(@start)
Set @start =@start+1
END

Ans:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
SELECT SUBSTRING(‘omkar@gmail.com’,CHARINDEX(’@’,‘omkar@gmail.com’)
+1),len(‘omkar@gmail.com’- CHARINDEX(’@’ ,‘omkar@gmail.com’))
SELECT SUBSTRING(Email,CHARINDEX(‘@’,Email)+1,LEN(Email)-CHARINDEX(‘@’,Email))

SELECT DATENAME(DAY,’2012-09-30 12:43:46.837’) –Returns 30


SELECT DATENAME(WEEKDAY,’2012-09-30 12:43:46.837’) Returns Sunday
SELECT DATENAME(MONTH,’2012-09-30 12:43:46.837’) Returns September

SCHEMABINDING:
SCHEMABINDING specifying the function is bound to the database objects that it references.
If we drop the reference table its indicating the reference function cannot perform action So.
CREATE FUNCTION fn_GetNamebyID(@id int)
Returns Name nvarchar(50)
WITH SCHEMABINDING
As
Begin
Return(select Name from tblemployees where id=@id)
END

Temporary Tables
1) Local temp tables
Create table #sample_table (id int, Name nvarchar(50))
Same connection
2) Globaltemptables
Create table ##sample_table (id int, Name nvarchar(50))
In all the connections

INDEX:
Index is to help to find the date in faster way.
CREATE INDEX IX_tblemployee_salary
ON tblEmployee (salary asc)
Sp_helptext IX_tblemployee_salary

CLUSTERD INDEX- Determines the physical order of data in a table.


Only 1 clustered index have in a table.
A primary key column can have automatically created an cluster index.
NON-CLUSTERD INDEX – Determines the pointer to the location of the data.

VIEW:
View is nothing more than a saved SQL Query, it’s a virtual table(doesn’t store any data).
Ex:
Create view vw_EmployeebydepartmentName
As
Select id,Name,salary,gender,departmentname
From tblemployee
Join tbldepartment
On tblemployee.deptid= tbldepartment.deptid
 We cannot pass a parameter to a view instead we can use inline table valued functions.
 Cannot create a views on temp tables.
 ORDER BY clause cannot apply in views.

TRIGGERS:
1. After triggers (For Triggers)
2. Instead OF
DML Triggers
DDL Triggers
Logon Triggers
FOR INSERT  create an special table inserted
FOR DELETE  create an special table deleted
After triggers (For Triggers)
1)
Create Trigger Tr_tblEmployee_ForInsert
On tblEmployee
FOR INSERT
As
Begin
Declare @id int
Select @id=id from inserted
Insert into tblemployeeAudit values(‘New employee with id =’ + cast (@id as nvarchar(5)) + ‘is added at ’
+cast(getdate()as nvarchar(20)))
End
2)
Create Trigger Tr_tblEmployee_ForDelete
On tblEmployee
FOR DELETE
As
Begin
Declare @id int
Select @id=id from deleted
Insert into tblemployeeAudit values(‘An Existing with id =’ + cast (@id as nvarchar(5)) + ‘is deleted at ’ +
cast(getdate()as nvarchar(20)))
End
3)
Create Trigger Tr_tblEmployee_ForUpdate
On tblEmployee
FOR UPDATE
As
Begin
Select * from deleted
Select * from inserted
End

While(Exists(select id from #temptable)) TRUE or FALSE


INSTEAD OF Trigger
Instead Of Insert
Create trigger tr_vwtblemployeedetails_InsteadOFInsert
On vwEmployeeDetails
Instead of insert
As
Begin

declare@Deptid int
select @Deptid=Deptid from tbldepartment
join inserted
on inserted. Deptname= tbldepartment. Deptname
if (@Deptid is NULL)
Begin
Raiseerror(‘Invalid Department Name.’,16,1)
Return
Insert into tblEmployee(Id, Name,Gender,DeptId) select id,Name, Gender,@DeptId from inserted

End
Instead Of Update

Create trigger tr_vwtblemployeedetails_InsteadOFUpdate


On vwEmployeeDetails
Instead of Update
As
Begin

If update(id)
begin
Raiseerror(‘we cannot changed the ID’,16,1)
Return

If update(DeptName)
Begin
Declare Deptid int
Select @deptid=deptid from tbldepartment join inserted on inserted. DeptName= tbldepartment.
DeptName

If (deptId is Null)
Begin
Raiseerror(‘Invalid Department Name.’,16,1)
Return
End
Update tblEmployee set deartmentid=@depatId from inserted
Join tblemployee on tblemployee.id=inserted,id
End

If update(gender)
Begin
Update tblEmployee set gender=inserted.gender
From inserted
Join tblemployee on tblemployee.id=inserted,id
End

If update(Name)
Begin
Update tblEmployee set Name=inserted.Name
From inserted
Join tblemployee on tblemployee.id=inserted,id
End

End

Instead Of Delete

Create trigger tr_vwtblemployeedetails_InsteadOFDelete


On vwEmployeeDetails
Instead of delete
As
Begin

Delete tblemplyee from tblemplyee join deleted on tblemplyee.id= deleted .id


--Sub query
Delete from tblemplyee where id in (select id from deleted)
End

Table Variable:
Table variable and temp tables are cteated in tempDB
View:
Create view vwEmployeecount
As
Select deptName,DepartmentId,Count(*) TotalEmployees from tblEmployee join tbldepartment
on tbldepartment.deptId= TotalEmployees. DepartmentId
group by deptName,DepartmentId

select deptName, TotalEmployees from vwEmployeecount where TotalEmployees>=2

TempTables:

Select deptName,DepartmentId,Count(*) TotalEmployees into #TempEmployeesCount


From tblEmployee join tbldepartment
on tbldepartment.deptId= TotalEmployees. DepartmentId
group by deptName,DepartmentId

select deptName, TotalEmployees from #TempEmployeesCount where TotalEmployees>=2

Table variable

Declare @TblEmployeecount table (deptName nvarchar(20), DepartmentId int, TotalEmployees int)


Insert @TblEmployeecount
Select deptName,DepartmentId,Count(*) TotalEmployees into #TempEmployeesCount
From tblEmployee join tbldepartment
on tbldepartment.deptId= TotalEmployees. DepartmentId
group by deptName,DepartmentId

select deptName, TotalEmployees from @TblEmployeecount where TotalEmployees>=2

Derived Table

Select deptName, TotalEmployees From


(
Select deptName,DepartmentId,Count(*) TotalEmployees into #TempEmployeesCount
From tblEmployee join tbldepartment
on tbldepartment.deptId= TotalEmployees. DepartmentId
group by deptName,DepartmentId
)
As EmployeeCount
Where TotalEmployees>=2
CTE
WITH EmployeeCount(deptName, DepartmentId, TotalEmployees)
AS
(
Select deptName,DepartmentId,Count(*) TotalEmployees
From tblEmployee join tbldepartment
on tbldepartment.deptId= TotalEmployees. DepartmentId
group by deptName,DepartmentId
)
Select deptName, TotalEmployees
From
EmployeeCount Where TotalEmployees>=2

CTE is an Temporary resultset

WITH CTE_Name(Col1,Col2..)
AS
(
CTE Query
)

WITH EmployeeCount(DepartmentId, TotalEmployees)


AS
(
Select DepartmentId,Count(*) TotalEmployees
From tblEmployee
group by DepartmentId
)
Select deptName, TotalEmployees
From tbldepartment join
EmployeeCount
On EmployeeCount. DepartmentId= tbldepartment.deptid
Order by TotalEmployees

More than 1 CTE’s can be create and used for immediate SELECT,UPDATE,INSERT,DELETE statements

It is possible to UPDATE a CTE Yes & NO

If CTE created one Base table then Update is possible


If CTE created multiple table and update an base table its also possible.
BUT, If CTE created multiple table and update both tables its NOT possible.
NORMALIZATION
Organizing the data reduces the data redundancy and the data consistency.
 Disk space wastage
 Data inconsistency
 Difficult to perform DML

Normal Forms
1NF
 Data should atomic , No multiple values seperate with commas
 Repeating the column groups
 Identify the unique by using Primarykey
2NF
 Data meet the 1NF conditions
 Move redundant data into separate table
 Create the relationships by using foreign keys
3NF
 Meet all the 1NF and 2NF conditions
 Doesn’t contains the columns that are fully dependent upon the primary key (Computed
columns not required)

PIVOT
ErrorHandling:
Create proc SpsellProduct
@productId int
@QunatityToSell
AS
Begin
--Check the stock availabale, for the product we want to cell
Declare @StockAvailable
Select @StockAvailable=QtyAvailable form tblProduct where @productid= productid
If(@StockAvailable < @QunatityToSell)
Begin
RaiseError(‘Stock not available’,16,1)
End
--If Enough stock available
Else
Begin
Begin Tran
--First Reduce the Quantity Available
Update tblProduct set QtyAvailable=( QtyAvailable - @QunatityToSell )
Where productid= @productid

Declare @MaxProductSalesID Int


Select @MaxProductSalesID = Case When Max(ProductSalesID) IS NULL
Then 0 else MAX(ProductSalesID)
End
From tblProductsales
--Incement MaxProductSalesID by 1 ,so we don’t get priparykey violation

SET @MaxProductSalesID = @MaxProductSalesID + 1

Insert into tblProductsales values (@MaxProductSalesID, @productid, @QunatityToSell)


If(@@ERROR <> 0)
Begin
Rollback Transaction
Print’ Transaction Rollback Back’
Else
Commit Transaction
End

End

@@ERROR is cleared and reset on each statement execution.


In 2005 TRY CATCH Block will handle the situation

Create proc SpsellProduct


@productId int
@QunatityToSell
AS
Begin
--Check the stock availabale, for the product we want to cell
Declare @StockAvailable
Select @StockAvailable=QtyAvailable form tblProduct where @productid= productid
If(@StockAvailable < @QunatityToSell)
Begin
RaiseError(‘Stock not available’,16,1)
End
--If Enough stock available
Else
Begin
Begin TRY
Begin Tran
--First Reduce the Quantity Available
Update tblProduct set QtyAvailable=( QtyAvailable - @QunatityToSell )
Where productid= @productid

Declare @MaxProductSalesID Int


Select @MaxProductSalesID = Case When Max(ProductSalesID) IS NULL
Then 0 else MAX(ProductSalesID)
End
From tblProductsales
--Incement MaxProductSalesID by 1 ,so we don’t get priparykey violation

SET @MaxProductSalesID = @MaxProductSalesID + 1

Insert into tblProductsales values (@MaxProductSalesID, @productid, @QunatityToSell)

Commit Transaction
End Try
Begin Catch
Rollback Transaction
Select ERROR _NUMBER() as ErrorNumber,
ERROR_MESSAGE() as ErrorMessage,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_STATE() as ErrorState,
ERROR_SEVERITY() as ErrorSeverity,
ERROR_LINE() as ErrorLine
End Catch
End

End

TRANSACTIONS:

Begin Transaction
Process database commands
Check if any Errors
If error occurred,
Rollback Transaction
Else,
Commit Transaction
In second Connection fire the query
A Successful Transaction must pass the ACID Test.
A – Atomocity All statements in the transaction either completed successfully or they were all rolled
back. The tsk that the set of operations represents either accomplished or not, But in any case not left
half done.

C – Consistancy All data touched by the transaction is left in a logically consistent state. For example
stockavailable numbers are dcremented from tblProduct then, there has to be a related entry in
tblProductSales ,the inventory can’t just disappear (may be power cut system)

I – Isolated The Transaction must affect data without interfering with other concurrent transactions or
being interfered with by them.
Most databases use locking to maintain transaction isolation.
D – Durability Once a change is made, it is permenant. If system error or power failure occers before a
set of commands is complete , those commands are undone and the data is restored to its original state
once the system begins running state.
If 1,2,3,4,5,6,7,8 list of commands esecuting, power failure in middle and the system restarts now the
database has in the position to rolled back or Undo the transaction stage.

LIST of Tables in the Database

Select * from sysobjects


 Represents Tables
Select * from sysobjects where xtype=’U’
‘U’ means User Table
FN – Functions
P – Stored Procedures
V – Views

Select * from sys.tables


Select * from sys.views
Select * from sys.prosedures

Select * from INFORMATION.SCHEMA.TABLES


Select * from INFORMATION.SCHEMA.VIEWS
Select * from INFORMATION.SCHEMA.ROUTINES –Stored Procedures

You might also like