I'm using Laravel with SQLSRV connection and want to do union query to get results from multiple tables, but there is an error that display with sqlsrv but working good with mysql.
I will provide my code to check:
$courses = DB::table('courses')
->where('courses.name', 'like', '%'.$search_text.'%')
->selectRaw(
'id, courses.name as name, courses.created_at as created_at,
(CASE
WHEN courses.is_program = 1 THEN "Program"
WHEN courses.is_program = 0 THEN "Course"
ELSE "Unknown"
END) AS type'
);
$surveys = DB::table('surveys')
->where('surveys.name', 'like', '%'.$search_text.'%')
->selectRaw(
'id, surveys.name as name, surveys.created_at as created_at,
(CASE
WHEN surveys.id != 0 THEN "Survey"
ELSE "Unknown"
END) AS type'
);
$exhibitions = DB::table('exhibitions')
->where('exhibitions.name', 'like', '%'.$search_text.'%')
->selectRaw(
'id, exhibitions.name as name, exhibitions.created_at as created_at,
(CASE
WHEN exhibitions.id != 0 THEN "Exhibition"
ELSE "Unknown"
END) AS type'
);
$results = $courses->unionAll($surveys)->unionAll($exhibitions);
if ($perPage) {
$results = $results->paginate($perPage);
} else {
$results = $results->get();
}
The error with SQLSRV is:
SQLSTATE[42S22]: [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Invalid column name 'Program'
Can anyone help me please?
The problem is with CASE WHEN THEN statement.