SQL

SQL Case Statement Example

By July 31, 2017 No Comments

Basic syntax for using case when statements in SQL.

For this example we want the following:

If Field1 = 2 and Field2 = 2 then use the date in Field3 else use ‘1/1/3000’.

Here is our table and generic data insert:

CREATE Table #Test(
	Field1	int,
	Field2	int,
	Field3	datetime
)

INSERT INTO #Test
(Field1, Field2, Field3)
VALUES
(2, 1, '1/1/2017'),
(2, 2, '1/2/2017'),
(2, 1, '1/3/2017'),
(2, 2, '1/4/2017'),
(2, 2, '1/1/2017')

Here is the statement using case when:

select case when Field1 = 2 and Field2 = 2 then Field3 else '01/01/3000' end as Field3
from #Test

Leave a Reply