Advanced Search in Linq to SQL possible? - linq-to-sql

Without the use of "LIKE" in Dynamic Linq it virtually renders it useless to me when trying to create an advanced search query.
How have any of you overcome this Advanced Search problem when using Linq to SQL?
I'd need to search the following field types and they all could be null as well:
List item
varchar (column LIKE '%' + myText + '%')
text (column LIKE '%' + myText + '%')
DateTime (column >= myDate - if the "myDate" is not null of course)
integer (column = myInt - if "myInt" is not null of course)
boolean
I also can't just use ExecuteQuery because then I don't get a true "entity" and all of it's relations/associations.
I just don't see how I can do this with Linq to SQL. I'm currently without Stored Procs so I'd rather not have one stored proc just for this if I can figure this out with Linq.

To make LIKE Statements, you can use the Contains method:
string myText = "test";
var query = dc.Table.Where(r=>r.Column.Contains(myText));
This will generate this kind of SQL Statement:
SELECT [t0].[Column], ... [t0].[ColumnN]
FROM [Table] AS [t0]
WHERE [t0].[Column] LIKE #p0
And the #p0 parameter will have "%test%" as value.
For the Date and int comparison if I understand correctly what do you want, you could do this:
DateTime? myDate = new DateTime(2009, 3, 15);
var query = dc.Table.Where(r=> r.DateColumn > myDate || myDate == null );
So, if myDate is null, the condition DateColumn > myDate wont be evaluated.

Related

Mysql) when i using user-defined variable , SQL explain use type "ALL"

When i using user-defined variable , i want to use 'index' like 'ref..';
for example,
SET #company_code = "A002";
select *
from product_in_out
where company_code = #company_code
and product_date = "2022-04-13"
and out_type = "Q"
;
above result like this,
[enter image description here][1]
for using SQL index, i've tested that variable to plain text like "A002".
at that time, SQL use index like 'ref'
select *
from product_in_out
where company_code = "A002"
and product_date = "2022-04-13"
and out_type = "Q"
;
if so, is there any good way to use valiable for using mysql Index?!?!
As a workaround, add this composite index:
INDEX(out_type, product_date, company_code)
(I assume product_date is of datatype DATE.)

MySQL function IFNULL is not working correctly with Wildcards

I have a SQL Script where I am using wildcard in If Null statement.
I am looking to show all other records regardless of field has null values in it.
SELECT * FROM ABC WHERE (Value=1 AND
Prefix like IFNULL(${parameter:X},'%')
AND
Base like IFNULL(${parameter:Y},'%')
AND
Suffix like IFNULL(${parameter:Z},'%')
AND
Area like IFNULL(${parameter:Ax},'%')
);
I am expecting the result should show all values regardless if Area filed value is null
Don't use like. It will filter out NULL values in the data. Just do:
WHERE (NewestVersion = 1 AND
(Prefix like ${param:PrefixLookup} or ${param:PrefixLookup} is null) AND
(Base like ${param:BaseLookup} or ${param:BaseLookup} is null) AND
(Suffix like ${param:SuffixLookup} or ${param:SuffixLookup} is null) AND
(Custom2 like ${param:DRELookup} or ${param:DRELookup} is null)
If you have empty strings, then comparisons to NULL will not help. Just use:
WHERE (NewestVersion = 1 AND
(Prefix like ${param:PrefixLookup} or ${param:PrefixLookup} = '') AND
(Base like ${param:BaseLookup} or ${param:BaseLookup} = '') AND
(Suffix like ${param:SuffixLookup} or ${param:SuffixLookup} = '') AND
(Custom2 like ${param:DRELookup} or ${param:DRELookup} = '')

What's wrong with this SQL query WHERE AND clause?

Previously, this was working:
$patient_story_set_photos = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patientID = '.$post->ID.' AND patient_display = 1');
However, when I try to add another AND condition like this:
$patient_story_set_photos = $wpdb->get_results('SELECT * FROM wp_before_after WHERE patientID = '.$post->ID.' AND patient_display = 1 AND period_taken = '.$set->period_taken);
I get the following error on screen:
WordPress database error: [Unknown column '1hour' in 'where clause']
SELECT * FROM wp_before_after WHERE patientID = 8175 AND patient_display = 1 AND period_taken = 1hour
Can't see why there's a problem, are you not allowed to use multiple AND conditions in SQL?
The problem is not the AND, the problem is your 1hour, 1hour unquoted means a reference to an object (database, table) named 1hour, you need to quote '1hour'.
If you write
SELECT * FROM wp_before_after
WHERE patientID = 8175
AND patient_display = 1
AND period_taken = '1hour'
you will compare the field periodtaken to a string (CHAR,VARCHAR,TEXT) equal to '1hour'.
I assume period_taken is a field typed CHAR,VARCHAR or TEXT
Before anything, DO NOT CONCATENATE SQL STRINGS nowadays it is a MUST (see how to do it properly https://stackoverflow.com/a/60496/3771219)
The problem you are facing is because, I presume, that the period_taken field is some sort of Char/Varchar/String field and when you are filtering by a "Stringy" field you must sorround your literals values with single quotes:
SELECT *
FROM wp_before_after
WHERE patientID = 8175
AND patient_display = 1
AND period_taken = '1hour'
Hope this help

How do I write a Linq to SQL query with a cast?

How do i write a Linq to SQL query that translates into the following:
SELECT CAST(DATETEXT AS datetime) FROM mytable
var dates = from row in mytable
select DateTime.Parse(row.DATETEXT);
There are method overloads for DateTime.Parse that allow you to specify a format.
actually, you won't be needing that. just parse it as datatime when you will use the field value. here is an exaple;
var query = from c in mytable
select c;
then when you will use it;
DateTime _value = (DateTime)query.SingleOrDefault().DATETEXT
but if you wanna use it so much. here is an example;
NorthwindEntities _e = new NorthwindEntities();
public void poo() {
var query = from e in _e.Products
select DateTime.Parse(e.DateText);
}

LINQ to SQL - nullable types in where clause

I have a table with a column that has null values... when I try to query for records where that column IS NULL:
THIS WORKS:
var list = from mt in db.MY_TABLE
where mt.PARENT_KEY == null
select new { mt.NAME };
THIS DOES NOT:
int? id = null;
var list = from mt in db.MY_TABLE
where mt.PARENT_KEY == id
select new { mt.NAME };
Why?
after some more googling, I found the answer:
ref #1
ref #2
int? id = null;
var list = from mt in db.MY_TABLE
where object.Equals(mt.PARENT_KEY, id) //use object.Equals for nullable field
select new { mt.NAME };
This LINQ renders to SQL as follows:
((mt.PARENT_KEY IS NULL) AND (#id IS NULL))
OR ((mt.PARENT_KEY IS NOT NULL) AND (#id IS NOT NULL) AND (mt.PARENT_KEY = #id))
One possibility - if mt.PARENT_KEY is of some other type (e.g. long?) then there will be conversions involved.
It would help if you could show the types involved and the query generated in each case.
EDIT: I think I have an idea...
It could be because SQL and C# have different ideas of what equality means when it comes to null. Try this:
where (mt.PARENT_KEY == id) || (mt.PARENT_KEY == null && id == null)
If this is the case then it's a pretty ugly corner case, but I can understand why it's done that way... if the generated SQL is just using
WHERE PARENT_KEY = #value
then that won't work when value is null - it needs:
WHERE (PARENT_KEY = #value) OR (PARENT_KEY IS NULL AND #value IS NULL)
which is what the latter LINQ query should generate.
Out of interest, why are you selecting with
select new { mt.NAME }
instead of just
select mt.NAME
?) Why would you want a sequence of anonymous types instead of a sequence of strings (or whatever type NAME is?
It's definitely a matter of C# and SQL having different notions of how to compare nulls - the question has been addressed here before:
Compare nullable types in Linq to Sql