dbTalk Databases Forums  

Using IF inside SELECT ?

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Using IF inside SELECT ? in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Igor
 
Posts: n/a

Default Using IF inside SELECT ? - 04-19-2006 , 09:07 AM






Is there possibility to use IF conditions inside SELECT statements?

For example, can i write something like this:
CREATE PROCEDURE [search]
(
@OPTION int,
@KEYWORD nvarchar(40)
)
AS
BEGIN
SELECT id FROM projects WHERE title LIKE @KEYWORD IF (@OPTION = 1)
THEN (OR description LIKE @KEYWORD)
END

or am i limited to this:
....
BEGIN
IF @OPTION = 1
SELECT id FROM projects WHERE title LIKE @KEYWORD OR description LIKE
@KEYWORD
ELSE
SELECT id FROM projects WHERE title LIKE @KEYWORD
END


Reply With Quote
  #2  
Old   
Hugo Kornelis
 
Posts: n/a

Default Re: Using IF inside SELECT ? - 04-19-2006 , 09:33 AM






On 19 Apr 2006 07:07:47 -0700, Igor wrote:

Quote:
Is there possibility to use IF conditions inside SELECT statements?

For example, can i write something like this:
CREATE PROCEDURE [search]
(
@OPTION int,
@KEYWORD nvarchar(40)
)
AS
BEGIN
SELECT id FROM projects WHERE title LIKE @KEYWORD IF (@OPTION = 1)
THEN (OR description LIKE @KEYWORD)
END

or am i limited to this:
...
BEGIN
IF @OPTION = 1
SELECT id FROM projects WHERE title LIKE @KEYWORD OR description LIKE
@KEYWORD
ELSE
SELECT id FROM projects WHERE title LIKE @KEYWORD
END
Hi Igor,

The latter will probably perform best. But if you prefer to have it in
one query, you can also use

SELECT id
FROM projects
WHERE title LIKE @keyword
AND ( @option <> 1 OR description LIKE @keyword )

For more complex cases, check out the CASE expression in Books Online.

--
Hugo Kornelis, SQL Server MVP


Reply With Quote
  #3  
Old   
Helmut Woess
 
Posts: n/a

Default Re: Using IF inside SELECT ? - 04-19-2006 , 09:33 AM



Am 19 Apr 2006 07:07:47 -0700 schrieb Igor:

Quote:
BEGIN
IF @OPTION = 1
SELECT id FROM projects WHERE title LIKE @KEYWORD OR description LIKE
@KEYWORD
ELSE
SELECT id FROM projects WHERE title LIKE @KEYWORD
END
can be done this way:

SELECT id FROM projects WHERE title LIKE @KEYWORD OR
(@OPTION = 1 AND description LIKE @KEYWORD)

bye, Helmut


Reply With Quote
  #4  
Old   
Hugo Kornelis
 
Posts: n/a

Default Re: Using IF inside SELECT ? - 04-19-2006 , 10:48 AM



On Wed, 19 Apr 2006 16:33:26 +0200, Hugo Kornelis wrote:

Quote:
SELECT id
FROM projects
WHERE title LIKE @keyword
AND ( @option <> 1 OR description LIKE @keyword )
Oops, I misread the question. Use Helmut's version instead.

--
Hugo Kornelis, SQL Server MVP


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.