Use an unambiguous, set-based conversion and avoid changing server/session settings. Assuming the VARCHAR(10) column always contains a valid, consistent date format, the pattern is:
-- Example: column stores dates as 'YYYYMMDD'
SELECT ...
FROM dbo.YourBlobTable AS b
WHERE CONVERT(date, b.YourVarcharDateColumn, 112) >= DATEADD(YEAR, -3, CAST(GETDATE() AS date));
Key points:
- Use an unambiguous style code
- If the data is
YYYYMMDD, use style 112 (ISO, no delimiters) as above. - If the data is
YYYY-MM-DD,date/datetime2will interpret it correctly without a style for modern types, but using a style or normalizing toYYYYMMDDis safer and clearer. - Avoid ambiguous formats like
MM/DD/YYYYorDD/MM/YYYYfor storage and conversion.
- If the data is
- Filter on the converted date
- Convert the VARCHAR to
date(ordatetime2) in the predicate and compare to a date boundary:
- Convert the VARCHAR to
WHERE CONVERT(date, b.YourVarcharDateColumn, 112)
>= DATEADD(YEAR, -3, CAST(GETDATE() AS date));
- For performance and indexing
- If this table is large and the column is indexed as VARCHAR, converting in the WHERE clause prevents index seek usage.
- For best performance, add a persisted computed column of type
dateand index that:
ALTER TABLE dbo.YourBlobTable
ADD YourDateColumn AS CONVERT(date, YourVarcharDateColumn, 112) PERSISTED;
CREATE INDEX IX_YourBlobTable_YourDateColumn
ON dbo.YourBlobTable(YourDateColumn);
SELECT ...
FROM dbo.YourBlobTable
WHERE YourDateColumn >= DATEADD(YEAR, -3, CAST(GETDATE() AS date));
- Long-term recommendation
- Store dates in a proper date/datetime data type going forward (e.g.,
dateordatetime2) and only format as text in the presentation layer. This avoids reliance onDATEFORMATor language settings and uses the unambiguousYYYYMMDD/YYYY-MM-DDformats internally.
- Store dates in a proper date/datetime data type going forward (e.g.,
References: