Найти мой первый Cursor
запрос.
Примечание:
Здесь я использую Microsoft SQL Server 2012
Я беру идентификаторы из временной таблицы,Принимая во внимание, что вы используете фактическую таблицу.
И вы запрашиваете временную таблицу в результате.Но я создаю фактическую таблицу.
Вы должны начать с CountAgainstId
процедуры.
CREATE TABLE #Employee
(
EmpID int
, EmpName varchar (50) NOT NULL
, Salary int NOT NULL
, Address varchar (200) NOT NULL
)
GO
INSERT INTO #Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida')
, (1,'Mohan',12000,'Noida')
, (2,'Pavan',25000,'Delhi')
, (3,'Amit',22000,'Dehradun')
, (4,'Sonu',22000,'Noida'), (4,'Sonu',22000,'Noida')
, (5,'Deepak',28000,'Gurgaon'), (5,'Deepak',28000,'Gurgaon'), (5,'Deepak',28000,'Gurgaon')
GO
-- I inserted same rows.
SELECT * FROM #Employee
# Сотрудник:
EmpID EmpName Salary Address
1 Mohan 12000 Noida
1 Mohan 12000 Noida
2 Pavan 25000 Delhi
3 Amit 22000 Dehradun
4 Sonu 22000 Noida
4 Sonu 22000 Noida
5 Deepak 28000 Gurgaon
5 Deepak 28000 Gurgaon
5 Deepak 28000 Gurgaon
Запрос курсора:
create procedure RowCounts (
@EmpId int
, @Nos int output
, @RunTime int output
)
as
begin
declare @StartTime datetime
, @EndTime datetime
set @StartTime = (select getdate ())
set @nos = (select COUNT (*) from #employee where EmpID = @EmpId)
set @EndTime = (select GETDATE ())
/*
Do further, what do you want.
*/
set @RunTime = DATEDIFF (MILLISECOND, @StartTime, @EndTime)
end
*****************************************
create procedure CountAgainstId as
begin
declare @RowCount int
, @RunTime int
, @EmpId int
, @i int = 0
declare CountCursors cursor
static for
select empid from #employee
open CountCursors
fetch next from CountCursors into @empid
if OBJECT_ID ('dbo.Summaries') is null -- object_id() is not recognised the temp tables
begin
create table Summaries (Empid int, NoOfRow int, ExecutionTime int)
end
else
begin
truncate table Summaries
end
while @@FETCH_STATUS = 0
begin
if not exists (
select * from Summaries where empid = @EmpId -- for removing the duplicate empid's
)
begin
exec RowCounts @EmpId, @RowCount output, @RunTime output
insert into Summaries
values (@EmpId, @RowCount, @RunTime)
end
fetch next from CountCursors into @empid
end
CLOSE CountCursors
DEALLOCATE CountCursors
select * from Summaries
end
Конспект (Таблица вывода):
Empid NoOfRow ExecutionTime
1 2 0
2 1 0
3 1 0
4 2 0
5 3 0
Дайте мне знать, что вы получили.