SQL SERVER TUTORIAL IN DEPTH

The blog is to help users about sql server

Others

LightBlog

Breaking

Friday 25 June 2021

Friday 29 April 2016

April 29, 2016

Interview Question

--Get the second highest salary of HR department

select * from #employee1
select * from #department1

;with cte(empname,sal,row)
as
(
select empname,empsal,ROW_NUMBER() OVER (Order by empsal desc) AS RowNumber from #employee1 e
join #department1 d on e.depid=d.depid
where d.depname='HR'
)
select * from cte where row=2



Friday 7 November 2014

November 07, 2014

Order By Surname in a Table

select * from EmployeeDetail

Id EmployeeName
1 Anurag Nayak
2  Ritika mohanty
3     Siba Dalai
4 Biswa Panda

Trick 1 ;with cte(id,name,finalIndex,startIndex)as
(
select id,
EmployeeName,
LEN(EmployeeName) as LengthName,
CHARINDEX(' ',EmployeeName) as StartIndex from dbo.EmployeeDetail
)
select id,name,SUBSTRING(name,startIndex+1,finalIndex) as final from cte 
order by final


id       name                               final
3 Siba Dalai                       Dalai
2 Ritika mohanty
1 Anurag Nayak                Nayak
4 Biswa Panda                   Panda



Trick 2

select EmployeeName
from employeedetail
order by REVERSE(substring(reverse(EmployeeName),1,CHARINDEX(' ',reverse(EmployeeName))))

Tuesday 29 July 2014

July 29, 2014

One tricky question asked in interview on Having and group by Clause

select * from EmployeeSalary order by id














--o/p [Need employee id and the count that crossed more than 5000]
--employeeid and count(> 5000)
--1 1
--2 1
--3 2

select id,COUNT(EmployeeSalary) from EmployeeSalary
where EmployeeSalary > 5000
group by id







--Now i want those employees id who has more than 1 count [> 5000] salary.

select id,COUNT(EmployeeSalary) from EmployeeSalary
where EmployeeSalary > 5000
group by id
having COUNT(EmployeeSalary) >1








--> After Group by No Where clause we know that.





July 29, 2014

A nice way to truncate all the tables


I wanted to truncate all tables in a cursor. But I was unable to do it as some table were being reference by foreign key constraint.

This is the way I got it. 

1)Alter table with no check  constraint
2)Delete 
3)Alter table with Check Constraint
4) Reseed it

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
EXEC sp_MSForEachTable "DELETE FROM ?"
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
declare @table varchar(100)
declare NfrTable_cursor cursor
for
select TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'dbo'
and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME
open NfrTable_cursor
fetch next from NfrTable_cursor into @table
WHILE @@FETCH_STATUS = 0
BEGIN
 DBCC CHECKIDENT (@table, reseed, 0); 
fetch next from NfrTable_cursor into @table
end
close NfrTable_cursor
deallocate NfrTable_cursor

 test