I need to filter a field as date, but the field is not typed date or datetime.
SELECT champ_save_id, element_id, valeur
FROM g_champ_save AS cs
INNER JOIN g_champ AS c ON cs.champ_id = c.champ_id
WHERE cs.valeur <> '' AND NOT cs.valeur IS NULL
AND c.champ_code = 'qualif_valide_qualif_fin'
AND CONVERT(datetime, cs.valeur, 103) <= @filterdate
It throws an error (Conversion failed when converting datetime from character string) unless I comment the last line.
As I understand it, the SQL optimizer first executes the CONVERT function on every valeur field and , then filters on the other conditions, then joins. So it tries to CONVERT fields with “regular” text in it, so of course it does not work.
I tried with a CTE but it does exactly the same thing.
WITH valeurs AS (
SELECT champ_save_id, element_id, valeur
FROM g_champ_save AS cs
INNER JOIN g_champ AS c ON cs.champ_id = c.champ_id
WHERE cs.valeur <> '' AND NOT cs.valeur IS NULL
AND c.champ_code = 'qualif_valide_qualif_fin'
AND ISDATE(convert(datetime, cs.valeur, 103)) = 1
)
SELECT * FROM valeurs
WHERE CONVERT(datetime, valeur, 103) <= @filterdate
Do you have any idea which would allow me to be absolutely sure to first return the fields containing dates, and then filter them ?
The tables are designed like that (shortened for clarity) :
CREATE TABLE g_champ (
champ_id int IDENTITY(1,1) NOT NULL,
type_id int NOT NULL, -- defines the type : text, checkbox, date, etc
champ_code nvarchar(50) NULL,
champ_label nvarchar(max) NULL
)
CREATE TABLE g_champ_save (
champ_save_id int IDENTITY(1,1) NOT NULL,
champ_id int NOT NULL,
element_id int NULL,
valeur nvarchar(max) NULL
)
Thanks
I think you need to use IsDate: