MS SQLとOracleデータベースでのCASE WHENの使用方法


  1. 単純なCASE WHEN文の使用例:

MS SQL:

SELECT 
    column_name,
    CASE column_name
        WHEN 'value1' THEN 'result1'
        WHEN 'value2' THEN 'result2'
        ELSE 'result3'
    END AS result
FROM table_name;

Oracle:

SELECT 
    column_name,
    CASE column_name
        WHEN 'value1' THEN 'result1'
        WHEN 'value2' THEN 'result2'
        ELSE 'result3'
    END AS result
FROM table_name;
  1. 複雑な条件を含むCASE WHEN文の使用例:

MS SQL:

SELECT 
    column_name,
    CASE
        WHEN column_name = 'value1' AND another_column = 'value2' THEN 'result1'
        WHEN column_name = 'value3' OR (column_name = 'value4' AND another_column = 'value5') THEN 'result2'
        ELSE 'result3'
    END AS result
FROM table_name;

Oracle:

SELECT 
    column_name,
    CASE
        WHEN column_name = 'value1' AND another_column = 'value2' THEN 'result1'
        WHEN column_name = 'value3' OR (column_name = 'value4' AND another_column = 'value5') THEN 'result2'
        ELSE 'result3'
    END AS result
FROM table_name;
  1. CASE WHEN文を使用して列を更新する例:

MS SQL:

UPDATE table_name
SET column_name = 
    CASE
        WHEN column_name = 'value1' THEN 'result1'
        WHEN column_name = 'value2' THEN 'result2'
        ELSE 'result3'
    END;

Oracle:

UPDATE table_name
SET column_name = 
    CASE
        WHEN column_name = 'value1' THEN 'result1'
        WHEN column_name = 'value2' THEN 'result2'
        ELSE 'result3'
    END;

以上が、MS SQLとOracleデータベースでのCASE WHEN文の使用方法とコード例です。これを参考にして、データベースの条件に基づいて結果を返す柔軟なクエリを作成することができます。