Using IF ELSE inside View in SQL Server

Last Reply 7 months ago By dharmendr

Posted 7 months ago

Can we use IF ELSE inside a View?

Thanks

R

Posted 7 months ago

Hi Rockstar8,

Use CASE statement.

Check this below test query. Now please take its reference and correct your query.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

SQL

CREATE VIEW vwGetCustomerDetails AS
SELECT TOP 15 CustomerID
			,ContactName
			,CASE Country	
				WHEN 'USA' THEN 'United States of America'
				WHEN 'UK' THEN 'United Kingdom' 
			ELSE Country END 'Country'
			FROM Customers 
GO
SELECT * FROM vwGetCustomerDetails ORDER BY Country DESC

Output

CustomerID ContactName Country
BONAP Laurence Lebihan  United States of America
BSBEV Victorian Ashworth United Kingdom
CHOPS Yang Wang Switzerland
CENTC Francisco Chang Mexico
BERGS Christina Berglund  Italy
AROUT Thomas Hardy  Ireland
ANATR Ana Trujillo  France
BLAUS Hanna Moos  Finland
BLONP Frédérique Citeaux  Finland
BOTTM Elizabeth Lincoln Canada
COMMI Pedro Afonso Brazil
ANTON Antonio Moreno  Brazil
ALFKI Maria  Austria
BOLID Martín Sommer  Argentina
CACTU Patricio Simpson Argentina