problem with UNION ALL

i have the following stored procedure:

declare @BlogID int
set @BlogID = '19321'

declare @DateAdded smalldatetime
Set @DateAdded = (Select DateAdded From Blog Where BlogID = @BlogID)


Select Top 1 BlogID, Headline, Category1NAME, DateAdded
From Blog
Where DateAdded < @DateAdded
Order By DateAdded DESC

UNION ALL
Select Top 1 BlogID, Headline, Category1NAME, DateAdded
From Blog
Where DateAdded > @DateAdded
Order By DateAdded DESC


why does it come up as an error in UNION ALL?  Please help
attipaAsked:
Who is Participating?
 
BrandonGalderisiCommented:
This will eliminate the error.
declare @BlogID int
set @BlogID = '19321'
 
declare @DateAdded smalldatetime
Set @DateAdded = (Select DateAdded From Blog Where BlogID = @BlogID)
 
select * from 
(Select Top 1 BlogID, Headline, Category1NAME, DateAdded
From Blog
Where DateAdded < @DateAdded
Order By DateAdded DESC)a
UNION ALL
select * from (
Select Top 1 BlogID, Headline, Category1NAME, DateAdded
From Blog
Where DateAdded > @DateAdded
Order By DateAdded DESC)b

Open in new window

0
 
BrandonGalderisiCommented:
You can only ORDER after ALL union statements
declare @BlogID int
set @BlogID = '19321'
 
declare @DateAdded smalldatetime
Set @DateAdded = (Select DateAdded From Blog Where BlogID = @BlogID)
 
 
Select Top 1 BlogID, Headline, Category1NAME, DateAdded
From Blog
Where DateAdded < @DateAdded
 
UNION ALL
Select Top 1 BlogID, Headline, Category1NAME, DateAdded
From Blog
Where DateAdded > @DateAdded
Order By DateAdded DESC

Open in new window

0
 
attipaAuthor Commented:
that doesn't help because i need the blog row right before and right after the value i bring in.  is this possible?
0
 
Kevin CrossChief Technology OfficerCommented:
Try like this:
declare @BlogID int
set @BlogID = '19321'
 
declare @DateAdded smalldatetime
Set @DateAdded = (Select DateAdded From Blog Where BlogID = @BlogID)
 
 
select * 
from (
	Select Top 1 BlogID, Headline, Category1NAME, DateAdded
	From Blog
	Where DateAdded < @DateAdded
	Order By DateAdded DESC
) t
UNION ALL
select * 
from (
	Select Top 1 BlogID, Headline, Category1NAME, DateAdded
	From Blog
	Where DateAdded > @DateAdded
	Order By DateAdded DESC
) t

Open in new window

0
 
attipaAuthor Commented:
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.