I have several tables which typically have nullable "CreatedDate" and/or "ModifiedDate" datetime columns. I would like a query that can select from any single table where one, both, or neither datetime column exist and each column is BETWEEN provided (separate) ranges.
Here is a rough (non-working) example. This attempts to use COL_LENGTH to determine if a column exists. However, if a column is not present an error is thrown, I believe because the entire WHERE is still evaluated.
SELECT * FROM tableName
WHERE 1=1 AND
(COL_LENGTH(tableName, 'CreatedDate') IS NULL OR CreatedDate BETWEEN @CreatedFrom AND @CreatedTo) AND
(COL_LENGTH(tableName, 'ModifiedDate') IS NULL OR ModifiedDate BETWEEN @ModifiedFrom AND @ModifiedTo)
This is solvable with dynamic SQL. However, in this case I am restricted to read-focussed permissions. So no EXEC, CREATE, or INSERT.
Is this possible with static SQL?
Example tables
With both columns:
DECLARE @Table1 table
(
Id int NOT NULL,
CreatedDate datetime NULL,
ModifiedDate datetime NULL
);
INSERT @Table1
(Id, CreatedDate, ModifiedDate)
VALUES
(1, NULL, NULL),
(2, NULL, '20230101 01:23:45.678'),
(3, '20230101 02:34:56.789', NULL),
(4, '20230101 03:45:00.891', '20230101 04:56:00.789');
DECLARE
@CreatedFrom datetime = {TS '2023-01-01 01:30:00.000'},
@CreatedTo datetime = {TS '2023-12-31 23:30:00.000'},
@ModifiedFrom datetime = {TS '2023-01-01 06:00:00.000'},
@ModifiedTo datetime = {TS '2023-12-31 18:00:00.000'};
With one column:
DECLARE @Table2 table
(
Id int NOT NULL,
CreatedDate datetime NULL
);
INSERT @Table2
(Id, CreatedDate)
VALUES
(1, NULL),
(2, '20230101 02:34:56.789');
DECLARE
@CreatedFrom datetime = {TS '2023-01-01 01:30:00.000'},
@CreatedTo datetime = {TS '2023-12-31 23:30:00.000'};
Thank you @PaulWhite for the initial example.