Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create view with if else inside

Tags:

sql

sql-server

I want to make view or simply to get some data from database but in specific way.

For example if data is :

 1 | test | test | 0 | test  
 2 | test | test | 1 | test
 3 | test | test | 1 | test
 4 | test | test | 1 | test
 5 | test | test | 0 | test

The output should be:

 1 | test | test | FALSE | test  
 2 | test | test | TRUE  | test
 3 | test | test | TRUE  | test
 4 | test | test | TRUE  | test
 5 | test | test | FALSE | test

Any ideas?

like image 438
PowerPuffGirl Avatar asked Dec 08 '25 07:12

PowerPuffGirl


2 Answers

Use CASE expression.

Query

SELECT col1, col2, col3,
CASE col4 WHEN 0 THEN 'False'
WHEN 1 THEN 'TRUE' 
ELSE NULL END AS col4, col5
FROM your_table_name;
like image 157
Ullas Avatar answered Dec 09 '25 19:12

Ullas


An if condition in SQL is expressed using CASE expression:

SELECT
   id
,  a
,  b
,  CASE c WHEN 0 THEN 'FALSE' ELSE 'TRUE' END AS c
,  d
FROM my_table

Note that there are two forms of CASE expression in SQL Server - simple and searched. The above is an example of a simple.

like image 38
Sergey Kalinichenko Avatar answered Dec 09 '25 21:12

Sergey Kalinichenko