I was wondering what were the best practices for making a query in sql with a dynamic value, lets say i have a Value(nvarchar(max))
value: "912345678"
select * from AllData
where Number like '%912345678%'
value: "Michael"
select * from AllData
where Name like '%Michael%'
value: "Street number 10"
select * from AllData
where Address like '%Street number 10%'
This approuches are a bit slow since searching for a number that has 9 digits would be faster without % like this
select * from AllData
where Number like '912345678'
I use a EDMX to make a connection to an external database in C#, like this:
var Result = EDMXEntity.Entities.Where(x =>
(SqlFunctions.PatIndex("%" + Value.ToLower() +"%", x.Name.ToString().ToLower()) > 0)
|| (SqlFunctions.PatIndex("%" + Value.ToLower() +"%", x.Number.ToString().ToLower()) > 0)
|| (SqlFunctions.PatIndex("%" + Value.ToLower() +"%", x.Address.ToString().ToLower()) > 0)).Take(50).ToList();
How can i increase performance?
In some cases, static SQL is faster because of the resource use required to prepare the dynamic statement. In other cases, the same statement prepared dynamically issues faster, because the optimizer can make use of current database statistics, rather than the database statistics available at an earlier bind time.
Dynamic SQL has the advantage that a query is recompiled every time it is run. This has the advantage that the execution plan can take advantage of the most recent statistics on the table and the values of any parameters.
Using CTEs, for instance, you can use SELECT from <subquery> in Open SQL. In my case I needed to execute dynamic SELECT count( DISTINCT col1, col2, …) which is not possible in the regular OpenSQL.
Wildcard searches like these on varchar
/nvarchar
fields are going to to iterate over every character, more or less, for records that meet the critieria.
A great (and fast!) option for these kinds of searches is to:
CONTAINS
keyword when you search rather than wildcards.You mentioned looking for credible sources, here is a good read.
If using LIKE
and PATINDEX
didn't get you needed performance then you probably should write sp which will use FTS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With