What do you call the following expression?
(TableName == NULL) ? "0" : TableName
I have a sense of what it does, but would like to look up the whole syntax definition, however as there is no real descriptor in the expression I can't seem to find out what it's called.
3 Answers 3
It's what is known in programming as a Ternary Operator. It's common in C/C++, JavaScript and PHP (among other languages).
As tombom states, the idea is that it is a short-hand if
statement:
<condition> ? <true-case-code> : <false-case-code>;
SQL Server 2012 and above has it's own Ternary Operator in the form of the IIF
statement.
IIF(@type = 2, 1, 0)
-
1Marking this one as correct because it has a linked reference, and is the first answer that contains the actual name.Reaces– Reaces2015年05月12日 09:21:43 +00:00Commented May 12, 2015 at 9:21
This is short for
<if> ? <then> : <else>
at least in programming that is, like in C++ and so on.
This type of expression is called a Ternary operator. Its standard form is
condition ? value_if_true : value_if_false
Using your example of
(TableName == NULL) ? "0": TableName
if TableName == NULL then "0" is returned
if TableName !==Null then TableName is returned
You could rewrite the ternary expression as
if(TableName==NULL) then "0" else TableName
but this is more verbose than the original Ternary expression.