Is There StartsWith
or Contains
in T-SQL with Variables?
If you are looking for a quick check in T-SQL
using variables
, make LIKE
your new buddy:
**LIKE @Variable + '%'**
is your go-to when you want to find rows starting with@Variable
.**LIKE '%' + @Variable + '%'**
will be helpful when you need rows containing@Variable
.
Simply replace Table
and Column
with your actual table and column names, and specify your own @Term
.
Exploring the Depths: Going Beyond the Basics
Wildcards: The Heart and Soul of LIKE Statement
You will find the %
wildcard putting in the hard yards when using the LIKE
operator:
LIKE 'Data%'
matches "Database", "DataScience", and anything that starts with "Data".LIKE 'Data_'
is handy for matching "Data1", "Datax", but not "Data12"LIKE 'Data%Center_'
has the flexibility to match "DataCenter1" or "DataCenterA", giving flexibility a whole new meaning!
Coping with Case Sensitivity
Not everything is capital, so use UPPER()
or LOWER()
for consistent results:
Different Data Types: Cast Away!
When interacting with functions like SERVERPROPERTY
, which do not sing the "string" tune:
Switching Gears: CHARINDEX for StartsWith
CHARINDEX
, the LIKE
alternative that knows exactly where to start looking for a substring:
Brevity is the Soul of IIF Function
For the fans of compact syntax, IIF
function from SQL Server 2012 onwards is an absolute gem:
Interacting with PATINDEX for Advanced Patterns
Meet PATINDEX
, the next level in search functionality with a knack for pattern identification; Something regex fans would appreciate:
Practical Use-Cases: From Corner Cases to Daily Tasks
Dynamic String Patterns: One String to Search Them All
Dynamic SQL: Gives you the flexibility you always wanted but remember, with great power comes greater responsibility!
The Special Characters Dilemma
Escape special characters either with square brackets or the ESCAPE
keyword:
Multi-pattern Searches: More the Merrier
Wildcards can be pieced together to search for multi-pattern strings. A little bit of creativity goes a long way!
Avoid the Pitfalls: Keeping an Eye on Efficiency
In enterprise-level databases, excessive use of wildcards or leading %
in patterns might hinder performance. Indexed views or full-text indexing might be the saviors!
Was this article helpful?