Sunday, 14 June 2020

Cursor- Query run on all the databases on instance and find out how much time taking on each database



USE [JaiVermaDB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

--exec [SP_EventHistory]

Create PROCEDURE [dbo].[SP_EventHistory]
AS

TRUNCATE TABLE JaiVermaDB.dbo.[EventHistory]

SET NOCOUNT ON
DECLARE @db sysname;
DECLARE @S NVARCHAR(MAX);
DECLARE @i INT;
DECLARE @tDate DATETIME; 
DECLARE @tDate2 DATETIME;

SET @i = 0
SET  @tDate2 = GETDATE()

DECLARE cur CURSOR  FAST_FORWARD FOR SELECT name FROM master.sys.databases WHERE name NOT IN ('master','model','msdb','tempdb')

OPEN cur
FETCH NEXT FROM cur INTO @db
WHILE @@fetch_status=0

BEGIN

SET  @tDate = GETDATE()

SET @s=N'insert into JaiVermaDB.dbo.[EventHistory_New_Temp_Table]
SELECT  '''+@db +'''as [DBNAME],
m.username AS [User Name],
event_time AS [Event Time],
s.ordernumber AS [Order Number],
s.organizationName + ''('' + s.firstName + '' '' + s.lastName + '')'' AS [Account Name],

FROM ['+@db+'].[dbo].message_log m

LEFT JOIN ['+@db+'].[dbo].submission s on charindex(s.ordernumber,m.message,1)> 0 
LEFT JOIN ['+@db+'].[dbo].client u on u.username = m.username

WHERE event_type IN ( ''PlacedOrder'',''ModifiedOrder'')
AND message not like ''Order Error found%''
and s.ordernumber is not null
and event_time >= DATEADD(Week, DATEDIFF(Week, -1, getdate()) - 1, 0)
and event_time <=   DATEADD(ss, -1, DATEADD(week, DATEDIFF(week, 0, getdate()), 0))

ORDER BY event_time'
  
  
EXEC sp_executesql @s
--print @s 

SET @i = @i + 1
PRINT ' --- Time taken each table ' + CONVERT(VARCHAR, @i) + ' name: ' + @db + ' --- in ' + CONVERT(VARCHAR,DATEDIFF(second, @tDate, GETDATE())) + ' secs'
FETCH NEXT FROM cur INTO @db

END

CLOSE cur
DEALLOCATE cur

PRINT  ' ======= Time taken for All tables in ' + CONVERT(VARCHAR,DATEDIFF(second, @tDate2, GETDATE())) + ' secs'


No comments:

Post a Comment