Link to home
Create AccountLog in
Avatar of Tristan Shortland
Tristan ShortlandFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Very slow sql query using while loop and like select

I have the attached SQL query which taking hours to run. It badly needs optimising but I'm no SQL expert!
Any help greatly appreciated!

I think it's the like bit which is slowing the query down as the query strings table is massive.

Thanks,
Tristan
DECLARE @StartTime		DATETIME
DECLARE @EndTime		DATETIME
DECLARE @CatStart		INT
DECLARE @CatEnd			INT
DECLARE @TheDay			DATETIME
DECLARE @TheDayPlusOne	DATETIME
DECLARE @TheCat			INT
DECLARE @Count			INT
DECLARE @Search			VARCHAR(10)
 
SET @StartTime =		'April 17 2008'
SET @EndTime =			'June 17 2008'
SET @CatStart =			1
SET @CatEnd =			11
SET @TheDay =			@startTime
SET @TheDayPlusOne =	        DATEADD(DAY, 1, @TheDay)
SET @TheCat =			@CatStart
 
SET NOCOUNT ON
WHILE @TheDay < @endTime
BEGIN
	WHILE @TheCat < @CatEnd
	BEGIN
		SET @Search =	'%cat=' + CAST(@TheCat AS VARCHAR) + '%'
		SET @Count =	( 
		
		SELECT COUNT (DISTINCT WS.[UNIQUE_IDENTIFIER_ID]) 
		FROM [WAP_SESSIONS] AS WS
		INNER JOIN [PAGE_HITS] AS PH ON WS.[WAP_SESSION_ID] = PH.[WAP_SESSION_ID]
		INNER JOIN [QUERY_STRINGS] AS QS ON PH.[QUERY_STRING_ID] = QS.[QUERY_STRING_ID]
		WHERE QS.[QUERY_STRING] LIKE @Search
		AND WS.[CLIENT_ID] = 50510
		AND WS.[DATE_CREATED] BETWEEN @TheDay AND @TheDayPlusOne
 
		 )
 
		PRINT CAST(@TheCat AS VARCHAR) + ', ' + CAST(@TheDay AS VARCHAR) + ', ' + CAST (@Count AS VARCHAR)
		SET @TheCat =	@TheCat + 1		
	END
	SET @TheCat =		@CatStart
    SET @TheDay =		DATEADD(DAY, 1, @TheDay)
	SET @TheDayPlusOne =DATEADD(DAY, 1, @TheDay)
END
 
SET NOCOUNT OFF

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Patrick Matthews
Patrick Matthews
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Tristan Shortland

ASKER

Hi,
I ended up doing a select where query_string like %cat=% into a temp table and then running the above query using that temp table.
This sped it up massively (from returning 10 rows in 18 minutes to 300 in about 5!).
Thanks for your help,
Tristan