swat
swat

Reputation: 79

How to do IF...ELSE like programming in SQL Server 2008

How can I do IF..Else like programming in T-SQL?

For example:

SELECT YEAR FROM TABLE;
IF (YEAR =  2015)
{ // do something }
ELSE IF (YEAR = 2016)
{ // do something }

I am trying to achieve this with stored procedure.

Suggestions are welcome ..as I am newbie to the programming world..

Upvotes: 1

Views: 75

Answers (2)

Thielicious
Thielicious

Reputation: 4442

As the question was edited before I added this answer, I did not know before that the OP was pointing at T-SQL. Yet, I will leave this here just for people that are interested how it could look in MySQL.

DELIMITER //
CREATE PROCEDURE Years ( yr INT ) 
  BEGIN 
    IF yr = 2015 THEN
      SELECT or whatever ...;
    ELSEIF yr = 2016 THEN
       DO something else...;
    END IF;
  END //
DELIMITER ;

Upvotes: 0

marc_s
marc_s

Reputation: 754348

You need to store that value you fetch from the table into a variable and then decide on that variable's value:

DECLARE @CurrYear INT;

SELECT @CurrYear = YEAR 
FROM TABLE;

IF (@CurrYear =  2015)
     -- do something
ELSE IF (@CurrYear = 2016)
     -- do something else

Upvotes: 3

Related Questions