Implicit conversion
I have taken AdventureWorks2017 database for this below query demo.
In Implicit conversion, we are comparing a [AccounNumber] varchar() with a value, which is also a varchar and after running this query once with Actual execution plan and Statistics ON, we find the more CPU time used and execution plan shows warning.
SET STATISTICS TIME ON
SELECT per.FirstName, per.LastName, per.BusinessEntityID, cust.AccountNumber, cust.StoreID
FROM Sales.Customer cust
INNER JOIN Person.Person per ON per.BusinessEntityID = cust.PersonID
WHERE AccountNumber = N'AW00029594'
GO
It shows more wired result when we run this query for 200 times, we found more CPU time and more execution time. approx more than 30 sec.
SELECT per.FirstName, per.LastName, per.BusinessEntityID, cust.AccountNumber, cust.StoreID
FROM Sales.Customer cust
INNER JOIN Person.Person per ON per.BusinessEntityID = cust.PersonID
WHERE AccountNumber = N'AW00029594'
GO 200
Explicit conversion
Whereas in explicit conversion, It shows more nice result when we run this query for 200 times, we found "0" CPU time and more execution time. approx less than 10 sec.
SET STATISTICS TIME ON
SELECT per.FirstName, per.LastName, per.BusinessEntityID, cust.AccountNumber, cust.StoreID
FROM Sales.Customer cust
INNER JOIN Person.Person per ON per.BusinessEntityID = cust.PersonID
WHERE AccountNumber = CONVERT(VARCHAR, N'AW00029594')
GO 200
Conclusion: Try to avoid write query, which does implicit conversion. So, either compare value with same data type or convert it explicitly
No comments:
Post a Comment