Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Adding a CASE WHEN in a WHERE clause
Message
From
29/07/2015 16:49:54
Walter Meester
HoogkarspelNetherlands
 
 
To
29/07/2015 16:24:27
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Environment versions
SQL Server:
SQL Server 2012
Application:
Web
Miscellaneous
Thread ID:
01622652
Message ID:
01622663
Views:
37
>>I would rewrite it into a form like
>>
>>
>>UPDATE Client
>>	SET DayBetweenFirstAcceptSoldDate = CASE WHEN ....WHEN ... WHEN ... THEN ... ELSE 0 END
>>	FROM Client
>>		LEFT JOIN BusinessTime ON ....
>>		LEFT JOIN Company ON ....
>>		LEFT JOIN Research ON ....
>>
>>
>>This will give the optimizer a chance to get you the best performance possible.
>
>Yes, I had that at first but this creates a too long command as I need to repeat pretty much the entire base command. By putting the CASE WHEN inside the WHERE clause, this allows to keep the core of the command as is but only to add an exception down below.


No you do not have to do that...


Consider the following. By no means error free, as I cannot test, but to give you an idea.

>>
UPDATE Client
	SET DayBetweenFirstAcceptSoldDate = ISNULL(Seconds,0)
	FROM Client
		LEFT JOIN (SELECT SUM(CASE WHEN ... THEN ... ELSE ... END  ) as seconds, ClientID as clientid2
                                 FROM Client 
					LEFT JOIN Company ON Company.NoCountry=1 AND Company.Numero=Client.NoCompany
					LEFT JOIN Research ON Research.NoCountry=1 AND Research.Numero=Client.NoResearch
					LEFT JOIN BusinessTime ON BusinessTime.NoProvince = COALESCE(Company.NoProvince, Research.NoProvince, 84) AND 
											BusinessTime.NoHoliday=0 AND
											BusinessTime.Start<Client.QueryDate AND
											BusinessTime.[End]>=Client.FirstAcceptDate
				WHERE 	Client.FirstAcceptDate>'1899-12-30 00:00:00.000' AND
						Client.QueryDate>'1899-12-30 00:00:00.000' AND
						Client.QueryDate>=Client.FirstAcceptDate AND
						(Client.NoCompany>0 OR Client.NoResearch>0)
				GROUP BY ClientID)  as Temp ON ClientId = ClientID2
You can run the subquery as a separate SELECT to check whether it produces the right results
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform