October 19, 2007 at 7:50 am
i have a code that looks like this:
IF EXISTS ( SELECT ID FROM ... )
SET @ID = SELECT TOP 1 ID FROM ...
...some code...
ELSE
...something else....
i'm executing the same SELECT twice.
is there a way i can do it only once?
i need to check if the result exists, before returning it.
thank you.
October 19, 2007 at 8:03 am
October 19, 2007 at 8:16 am
mrpolecat (10/19/2007)
declare @id intselect @id =( select top 1 n from tally where n > 5)
if @id is not null
begin
print 'yes'
print @id
end
else
begin
print 'no'
print @id
end
thanks.
i knew it was supposed to be something simple...
October 20, 2007 at 5:50 pm
Not sure what you're trying to do, but here's a different angle... think of it as a "set-based IF" 😀
SELECT TOP 1
CASE t.N WHEN NULL THEN 'No' ELSE 'Yes' END AS Status,
t.n
FROM dbo.Tally t,
(SELECT 1 One) d
WHERE N > 5
--Jeff Moden
Change is inevitable... Change for the better is not.
October 21, 2007 at 6:43 am
Jeff Moden (10/20/2007)
Not sure what you're trying to do, but here's a different angle... think of it as a "set-based IF" 😀
SELECT TOP 1
CASE t.N WHEN NULL THEN 'No' ELSE 'Yes' END AS Status,
t.n
FROM dbo.Tally t,
(SELECT 1 One) d
WHERE N > 5
:laugh:
i think if i'll use this approach the people who will be maintaining the database will kill me at some point... unless they know about Tally tables :hehe:
its nice, but i stick to the obvious.
October 21, 2007 at 11:01 am
No, no! The Tally table in this code was just to have a table to demonstrate from... I copied it from the previous post that MrPoleCat posted... (heh, you didn't say the same thing about his post 😀 ) Tally table doesn't even enter the picture, here...
--Jeff Moden
Change is inevitable... Change for the better is not.
October 21, 2007 at 12:06 pm
Jeff Moden (10/21/2007)
No, no! The Tally table in this code was just to have a table to demonstrate from... I copied it from the previous post that MrPoleCat posted... (heh, you didn't say the same thing about his post 😀 ) Tally table doesn't even enter the picture, here...
well i didnt understand your example at first (i do now)... but thats just proves my point.
MrPoleCat solution was easy to understand, yours is more complicated.
its a good one, but as i said other people need to understand what i'm doing.
i dont want people calling me asking to explain something i did a year ago 😛
October 21, 2007 at 12:35 pm
Heh... that's what "embedded comments" are for 🙂 But, I understand...
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply