I am working in a SQL Server environment, heavy on stored procedures, where a lot of the procedures use 0 and ” instead of Null to indicate that no meaningful parameter value was passed.
These parameters appear frequently in the WHERE clauses. The usual pattern is something like
WHERE ISNULL(SomeField,'') =
CASE @SomeParameter
WHEN '' THEN ISNULL(SomeField,'')
ELSE @SomeParameter
END
For various reasons, it’s a lot easier to make a change to a proc than a change to the code that calls it. So, given that the calling code will be passing empty strings for null parameters, what’s the fastest way to compare to an empty string?
Some ways I’ve thought of:
@SomeParameter = ''
NULLIF(@SomeParameter,'') IS NULL
LEN(@SomeParameter) = 0
I’ve also considered inspecting the parameter early on in the proc and setting it to NULL if it’s equal to ”, and just doing a @SomeParameter IS NULL test in the actual WHERE clause.
What other ways are there? And what’s fastest?
Many thanks.
Sorting out the parameter at the start of the proc must be faster than multiple conditions in a where clause or using a function in one. The more complex the query, or the more records that have to be filtered, the greater the gain.
The bit that would scare me is if this lack of nullability in the procedure arguments has got into the data as well. If it has when you start locking things down, your queries are going to come back with the “wrong” results.
If this product has some longevity, then I’d say easy is the wrong solution long term, and it should be corrected in the calling applications. If it doesn’t then may be you should just leave it alone as all you would be doing is sweeping the mess from under one rug, under another…
How are you going to test these changes, the chances of you introducing a wee error, while bored out of your skull making the same change again and again and again, are very high.