IF/ELSE in SQL (Control Structures)

Asked

Viewed 541 times

-2

Okay, I’m reading some articles on SQL control structures but I’m not getting a lot out of it, someone could explain how it works in a summarized form?

  • What is the condition you want to test? submit your code

2 answers

1


I usually use the When clause instead of IF, however....

Works similar to the programming structures of other languages.

In SQL Server, the IF statement ... ELSE is used to execute the code when a condition is TRUE or to execute a different code if the condition is evaluated as FALSE.

Nothing better than a few lines of code to see how it works

DECLARE @teste INT;
SET @teste = 15;

IF @teste < 20
   PRINT 'Acertou';
ELSE
   PRINT 'ERRRROU';
GO

RETURN: You got it right

As you can see he brought the hit because he entered the first true condition that the test was worth 15 and less (<) than 20

in a summarized form is this....

good link analysis; https://www.techonthenet.com/sql_server/loops/if_then.php

If you want to know about WHEN https://docs.microsoft.com/pt-br/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017

0

The SQL language itself does not have an IF/ELSE command. You will find such a command in procedural languages associated with your database manager. In SQL you can use the CASE/WHEN condional:

CASE WHEN condition THEN result
     [WHEN ...]
     [ELSE result]
END

In some cases the functions COALESCE and NULLIF can meet your needs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.