IF condition in SQL Server view

Is it possible to have an if condition in VIEWS

eg,

CREATE VIEW as DECLARE @Count int SET @Count=-1 select @Count=EmpID from EmployeeDetails where ID=200 IF @Count=-1 BEGIN SELECT * FROM TEAM1 END ELSE BEGIN SELECT * FROM TEAM1 END 
+6
source share
3 answers

No, I do not think this is possible.

Instead, you can use a stored procedure to achieve this functionality.

+2
source

You can try something forged with UNION:

 SELECT {fieldlist} FROM Table1 WHERE EXISTS(SELECT EmpID FROM EmployeeDetails WHERE ID = 200) UNION ALL SELECT {fieldlist} FROM Table2 WHERE NOT EXISTS(SELECT EmpID FROM EmployeeDetails WHERE ID = 200) 

This method will require that both SELECT statements return the same set of fields, although their sources may be different.

+8
source

Representations allow you to allow only those expressions that are specified in here

if you need to do if by column values ​​you can use

 SELECT CASE WHEN COLUMN1 = 1 THEN COLUMNX ELSE COLUMNY END FROM TABLE1 

if your need exceeds this, you must create a selection from a table-dependent function instead of a view.

You need a simple procedure

 CREATE PROCEDURE DOSOMETHING ( @ID INT ) AS BEGIN IF @ID > 100 SELECT 1 AS ID,'ME' AS NAME, GETDATE() AS VARIABLEDATECOL, NEWID() AS VARIABLEGUID ELSE SELECT 2 AS ID, 'YOU' AS NAME END 
+6
source

Source: https://habr.com/ru/post/886875/


All Articles