2

What is the when keyword used for in T-SQL?

when

NOTE: I tried searching this on the web (e.g. 'Googling')... however due to the ubiquitous nature of the word 'when', I wasn't able to find a good explanation.

Furthermore, a list of SQL keywords did not include 'when' so either the list was not exhaustive or it is unique to T-SQL (or perhaps it was added in some 'newer' version of T-SQL / SSMS). Link to this particular SQL keyword site: https://www.w3schools.com/sql/sql_ref_keywords.asp

1
  • 3
    Refer to the documentation for the CASE statement.
    – Lee Mac
    Commented Jun 12, 2019 at 19:31

2 Answers 2

3

It's used in conjunction with the CASE keyword, which is like a switch, or 'if' statement essentially... for example:

SELECT 
    CASE WHEN [Column] = 1 THEN 'Column is 1'
         WHEN [Column] = 2 THEN 'Column is 2'
         ELSE 'Column is not 1 or 2'
         END AS [Description]
0
2

WHEN is also part of MERGE statement:

Runs insert, update, or delete operations on a target table from the results of a join with a source table

MERGE
    [ INTO ] <target_table> [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias ]  
    USING <table_source>
    ON <merge_search_condition>  
    [ WHEN MATCHED [ AND <clause_search_condition> ]  
        THEN <merge_matched> ] [ ...n ]  
    [ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ]  
        THEN <merge_not_matched> ]  
    [ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]  
        THEN <merge_matched> ] [ ...n ]  
;
1
  • 1
    Thanks, this could be very useful for someone Commented May 11, 2020 at 20:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.