I’m not sure why the following subquery doesn’t work in SQL Server, when I run the subquery by itself it works just fine, but as soon as I add
Select * from ([subquery]) as table1
the query doesn’t run, SQL Server returns an error saying I have incorrect syntax near the keyword ‘if’, what syntax error exists here and how come it will work just fine otherwise?
Any pointers?
select * from (
if datepart(MONTH, getdate()) >= MONTH('1/February/0000')
--after february we want the next years semesters,
begin
select top 3 sem_name from semester_dates
where datepart(year, start_date) < datepart(YEAR, getdate()) and sem_name not like 'summer%'
end
else
begin
select top 3 sem_name from semester_dates sd
where datepart(year, start_date) >= datepart(YEAR, getdate()) and sem_name not like 'summer%'
end
) table1
You may want to consider moving your if/else logic into a table valued function. Something like this perhaps. Note, I didn’t check your logic, I just re-used this. You may need to adjust the code below accordingly: