I have a query that I’m building for an application. The database is setup in SQL Server 2008. I want to use a query similar to below, however, I will be using this ‘Where’ clause for about 4 other columns using the same requirements. Is this the appropriate way to test for null or ” in a column that is VarChar(255) and does allow nulls.
Ideally, if the variable @UutSerialNumber is null or empty (”), I want all the results, but if it is not, I want to use the ‘LIKE’ clause. Is this the proper way of doing this and will it work? It seems to work until I start adding more columns to the Where clause.
Also, how would I handle a “text” datatype using the same type of query?
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (UutSerialNumber LIKE '%' + @UutSerialNumber + '%' OR UutSerialNumber LIKE '%%' AND (@UutSerialNumber = '' OR @UutSerialNumber IS NULL)) AND ...
Help is appreciated. Thanks everyone!
It amy seem like duplication of SQL but the best way to do this is in terms of performace is using IF … ELSE
It can be done within the WHERE clause if you are doing it on multiple columns and the query you posted wasn’t far off it was just missing additional parenthesis along with having a redundant clause.
Convert the text type to VARCHAR(MAX).
as a footnote, I personally would use the CHARINDEX rather than concatenating strings in the like:
This is nothing more than a footnote however as I have done no performance testing, I just think it is easier on the eye!