Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF/ELSE Stored Procedure

Can anyone please point out what im doing wrong with this Stored Procedure please. I cant get it to compile and my software isnt giving any useful clues as to what is wrong with it.

CREATE PROCEDURE web.createSubscriptions
   (
   @Member_Id BIGINT,
   @Trans_type VARCHAR(100),
   @Payment_Status VARCHAR(100),
   @Payment_Date DATETIME,
   @Trans_Id VARCHAR(100)
   )

AS
DECLARE @tmpType VARCHAR(15)
BEGIN

INSERT INTO TBL_SUBSCRIPTIONS (subs_MemberID, subs_Type, subs_Status, subs_DateGenerated, subs_PaypalTransaction) VALUES(@Member_Id, @Trans_Type, @Payment_Status, @Payment_Date, @Trans_Id)

IF(@Trans_type = 'subscr_signup')
    BEGIN
    @tmpType = 'premium'
    END
ELSE(@Trans_type = 'subscr_cancel')
    BEGIN
    @tmpType = 'basic'
    END

UPDATE TBL_MEMBERS
SET members_Type = @tmpType
WHERE members_Id = @Member_Id

END
like image 588
Munklefish Avatar asked Nov 06 '09 14:11

Munklefish


People also ask

How do you do IF ELSE in SQL?

The IF ELSE statement Each IF statement has a condition. If the condition evaluates to TRUE then the statement block in the IF clause is executed. If the condition is FALSE , then the code block in the ELSE clause is executed. Finally, the IF clause checks if the sales amount in 2017 is greater than 10 million.

CAN YOU DO IF statements in SQL?

IF statements can be used to conditionally enter into some logic based on the status of a condition being satisfied. The IF statement is logically equivalent to a CASE statements with a searched-case-statement-when clause.

Can you have multiple select statements in a stored procedure?

Each procedure has one or more statements. In our case, these are SQL statements. So, you can write a procedure that will – insert new data, update or delete existing, retrieve data using the SELECT statement. And even better, you can combine more (different statements) in the stored procedures.

What is IIF SQL Server?

IIF is a shorthand way for writing a CASE expression. It evaluates the Boolean expression passed as the first argument, and then returns either of the other two arguments based on the result of the evaluation.


1 Answers

Nick is right. The next error is the else should be else if (you currently have a boolean expression in your else which makes no sense). Here is what it should be

ELSE IF(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

You currently have the following (which is wrong):

ELSE(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

Here's a tip for the future- double click on the error and SQL Server management Studio will go to the line where the error resides. If you think SQL Server gives cryptic errors (which I don't think it does), then you haven't worked with Oracle!

like image 57
RichardOD Avatar answered Oct 05 '22 11:10

RichardOD