jmasterx
jmasterx

Reputation: 54103

Conditional selection in SQL?

I have the following SQL code:

SELECT eml AS "Email Address"
FROM emailtbl
WHERE DEPT LIKE 'E%'

My issue is that if the department starts in 'F' I must select fax instead of eml. What could I do to select eml if the dept starts with 'E' and select fax if the dept starts in 'F'

Thanks

Upvotes: 4

Views: 119

Answers (2)

James
James

Reputation: 2911

How about this?

IF (SUBSTRING(@useLike,1,1) = 'E')
BEGIN
    SELECT eml AS "Email Address"
    FROM emailtbl
    WHERE DEPT LIKE @useLike

END
ELSE
BEGIN
    SELECT fax AS "Email Address"
    FROM emailtbl
    WHERE DEPT LIKE @useLike
END

Upvotes: 1

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58431

One option is to use a UNION ALL statement

SELECT eml AS "Entity"
FROM   emailtbl
WHERE  DEPT LIKE 'E%'
UNION ALL
SELECT fax AS "Entity"
FROM   emailtbl
WHERE  DEPT LIKE 'F%'

another one is to use a CASEstatement

SELECT CASE WHEN Dept LIKE 'E%' THEN eml ELSE fax END AS "Entity"
FROM   emailtbl
WHERE  DEPT LIKE 'E%' OR DEPT LIKE 'F%'

Upvotes: 9

Related Questions