Результаты из курсора во временную таблицу с количеством строк и временем выполнения - PullRequest
0 голосов
/ 03 декабря 2018

Необходимо извлечь 100 идентификаторов из таблицы Employee, используя курсор, затем выполнить хранимую процедуру и поместить количество строк и время выполнения для каждого идентификатора в одну временную таблицу.Какая-то идея, как посчитать количество строк, которые хранимая процедура будет ловить, и время выполнения для этого?

declare @temptable table
( ID nvarchar
 , numberOfRows int
 , executionTime int)

declare @id nvarchar(15)

declare db_cursor CURSOR FOR
select top 100 NationalIdNumber
from HumanResources.Employee

open db_cursor
fetch next from db_cursor into @id

while @@fetch_status = 0

begin

insert into @temptable

exec [dbo].[uspEmployeeData] @id

fetch next from db_cursor into @id

end

close db_cursor
deallocate db_cursor

Я использую SQL Server 2014 Standard edition

Ответы [ 2 ]

0 голосов
/ 03 декабря 2018

Найти мой первый 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

Дайте мне знать, что вы получили.

0 голосов
/ 03 декабря 2018

Вы можете сделать что-то вроде:

declare @tableresults TABLE (@id INT, row_count INT, durationms int)

DECLARE @starttime DATETIME

open db_cursor
fetch next from db_cursor into @id

while @@fetch_status = 0

begin

    SET @starttime = GETDATE()

    insert into @temptable
    exec [dbo].[uspEmployeeData] @id

    INSERT INTO @tableresults
    VALUES (@id, @@rowcount, DATEDIFF(millisecond, @starttime, GETDATE() )

    fetch next from db_cursor into @id
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...