Introduction
IIF is a short way for writing a CASE expression
IIF Function Introduced in SQL Server 2012
IIF Function Returns one of two the values, depending on whether the Boolean expression evaluates to true or false
SYNTAX OF IIF FUNCTION
IIF ( condition, TRUEvalue, FALSEvalue)
Description
Condition
Condtion that we want to check
Example : Returns Male as the boolean expression evaluates to TRUE
DECLARE @Gender INT
SET @Gender = 1
SELECT IIF( @Gender = 1, 'Male', 'Femlae') AS Gender
Output :
TRY_PARSE
Introduction
Introduced in SQL Server 2012
Converts a string to Date/Time or Numeric type
Returns NULL if the provided string cannot be converted to the specified data type
Requires .NET Framework Common Language Runtime (CLR)
SYNTAX OF TRY_PARSE FUNCTION
TRY_PARSE ( string_value AS data_type )
Example : Convert string to INT. As the string can be converted to INT, the result will be 99 as expected.
SELECT TRY_PARSE('99' AS INT) AS Result
SELECT TRY_PARSE('99' AS INT) AS Result
Output :
Example : Convert string to INT. The string cannot be converted to INT, so TRY_PARSE returns NULL
SELECT TRY_PARSE('ABC' AS INT) AS Result
Output :
SELECT TRY_PARSE('ABC' AS INT) AS Result
Output :
Use CASE statement or IIF function to provide a meaningful error message instead of NULL when the conversion fails.
Example : Using CASE statement to provide a meaningful error message when the conversion fails.
Example : Using CASE statement to provide a meaningful error message when the conversion fails.
SELECT
CASE WHEN TRY_PARSE('ABC' AS INT) IS NULL
THEN 'Conversion Failed'
ELSE 'Conversion Successful'
END AS Result
Output : As the conversion fails, you will now get a message 'Conversion Failed'instead of NULL
Example : Using IIF function to provide a meaningful error message when the conversion fails.
SELECT IIF(TRY_PARSE('ABC' AS INT) IS NULL, 'Conversion Failed',
'Conversion Successful') AS Result
What is the difference between PARSE and TRY_PARSE
PARSE will result in an error if the conversion fails, where as TRY_PARSE will return NULL instead of an error.
Since ABC cannot be converted to INT, PARSE will return an error
SELECT PARSE('ABC' AS INT) AS Result
Since ABC cannot be converted to INT, TRY_PARSE will return NULL instead of an error
SELECT TRY_PARSE('ABC' AS INT) AS Result