How to fin Max value among all the columns in a row in Sql Server

Sometimes we need max or min value among all the columns of a table for a each row. We all know how to do it for a column but needs little twist for a row. See below script to achieve it in Sql Server:

DECLARE @t TABLE(a INT,b INT,c INT,d INT,e INT,f INT );
INSERT @t VALUES(123,200,300,904,65,6),(9,8,7,11,56,0),(14,26,15,45,76,1)

SELECT *,(
SELECT max(val)
FROM (
VALUES(a),(b),(c),(d),(e),(f)
) AS value(val)
) as maxvalue
FROM @t t

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s