I am creating a report on SSRS 2008 R2. This report will only be sent when the data exists. At first, I tried to create data-driven subscription calling the stored procedure that checks if the view has data. If so, it will send the report to the defined recipients. Since the users ask to check the view every 10 mins, I set up a job to execute the job name of this data-driven subscription on SQL Server Agent. But I found out the subscription always timed out even though it only take around twenty to thirty seconds to select the view directly.
Then I tried to think other way to fulfill this requirement.
The way I tried is to create a stored procedure on SQL Server to check if the view has data first. If so, it will run the job name of the subscription created for the report on SSRS 2008 R2. In order to check the view every 10 mins, I created a job to execute this SP every 10 mins on SQL Server Angent.
The question is why it takes about 20 mins to execute SP1 with "IF EXISTS" but only 20 seconds to execute SP2 with "COUNT(*)". I'm really confused about it.
Thanks for your reply in advance. :)
SP1:
IF EXISTS (SELECT TOP 1 * FROM VIEW)
BEGIN
EXEC msdb.dbo.sp_start_job
@job_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
END
--
IF EXISTS (SELECT TOP 1 C1 FROM VIEW ORDER BY C1)
BEGIN
EXEC msdb.dbo.sp_start_job
@job_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
END
--
IF EXISTS (SELECT C1 FROM VIEW)
BEGIN
EXEC msdb.dbo.sp_start_job
@job_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
END
SP2:
DECLARE @ExecRowCount INT
CREATE TABLE #Temp
(
C1 CHAR(50),
C2 DECIMAL(10,0),
C3 CHAR(50),
C4 VARCHAR(4)
)
INSERT INTO #Temp
SELECT * FROM VIEW
SELECT @ExecRowCount = COUNT(*) FROM #Temp
DROP TABLE #Temp
IF(@ExecRowCount > 0)
BEGIN
EXEC msdb.dbo.sp_start_job
@job_name='xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
END
SP3:
IF ((SELECT COUNT(*) FROM VIEW) > 0)
BEGIN
EXEC msdb.dbo.sp_start_job
@job_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
END
Edit 2013/08/20: I added other clauses I tried in SP1 and SP3 @Click-Rex suggested.
Sorry I forgot to mention that the view is on SQL 2000. It's the root cause of this problem after I restored the related DBs of this view to SQL 2008 QAS to try. I didn't change any setting after restore.
The result is: The SP1 and SP3 takes less than 1 second and SP2 takes less than 20 seconds.
Actually, this view is quite complicated. I tried other simple views on SQL 2000. It didn't take too much time with "IF EXISTS".
Thanks for everyone's feedback. :-)