I am increasingly aware of the importance of making my queries efficient. It is crucial that I have the proper indexes etc. to make sure that my queries don't take up any more IO than is really necessary. But here is a query that is just ugly and I don't know how to make it efficient.
Let's say I have a table for stock items that looks something like this in its most basic form:
CREATE TABLE StockItems (
ItemID INT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
SerialNo VARCHAR (50) NOT NULL
);
Now I need to write a stored proc that will return all stock items for which the serial number matches a partial serial number provided. The following query would achieve exactly that:
SELECT * FROM StockItems WHERE SerialNo LIKE '%' + @SearchStr + '%'
But when I see a query like that I break out in cold sweat and clutch my comfort blanket tighter. There's no index on SerialNo
and even if there were, it would be of no help considering that I'm searching for a partial match.
Is there a way to achieve this task with queries that are more efficient?