September 28, 2015 at 7:20 am
I am interested in selecting certain tables to query from based on age of request.
Ex. If a person wants to query data that's > than 60 days old, Select * from TableA Else Select * From table B.
Thanks
September 28, 2015 at 7:44 am
declare @age int = 59
if @age > 60
begin
select * from tablea
end
else
begin
select * from tableb
end
Something like this? Or do you have a more complex scenario going on?
September 28, 2015 at 9:07 am
mbrady5 (9/28/2015)
I am interested in selecting certain tables to query from based on age of request.Ex. If a person wants to query data that's > than 60 days old, Select * from TableA Else Select * From table B.
Thanks
While the solution posted by Anthony will work, the question is how will that data be consumed? If it will eventually end up in some kind of report, then you may need to get this into a stored procedure, at which point making it work will require that the output of the query contain the exact same set of fields all the time. If both tables have exactly identical structures, you could also do it something like this:
DECLARE @AGE AS int = 59;
DECLARE @TODAY AS date = GETDATE();
SELECT *
FROM TABLEA
WHERE SomeDateField BETWEEN '1900-01-01' AND DATEADD(day, 0 - @AGE, @TODAY)
AND @AGE > 60
UNION ALL
SELECT *
FROM TABLEB
WHERE SomeDateField BETWEEN DATEADD(day, 0 - @AGE, @TODAY) AND @TODAY
AND @AGE <= 60;
If the two tables don't have the exact same set of fields, then you'll need to change the "*" to a specific list of fields for each SELECT, and use aliases when the same field from both tables has a different name in each one.
Steve (aka sgmunson) 🙂 🙂 🙂
Rent Servers for Income (picks and shovels strategy)
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply