I need to replace a where clause in a subquery with a clause that depend on the value of the master query.
I have to replace the full condition, not only the right side of the condition, so i have created a query like the one below :
SELECT p.par_des AS description,
COALESCE(
(SELECT SUM(ope_tot) FROM operator WHERE
(CASE WHEN p.par_cod = 'TEN01' THEN ope_cau = 'TEN01' OR ope_cau LIKE 'BAN__' ELSE ope_cau = p.par_cod END)
AND (ope_tim BETWEEN '00:00:00' AND '23:59:59' ) )
,0) AS value
FROM parameters p WHERE par_cod LIKE 'TEN__';
As you can see in the bold part of the query i replace a condition of the where clause based on the value of the field in the master query, and i have to specify also an or operator if the condition is satisfied .
This query work well on PostgreSQL and MySQL, but it doesn’t work in MSSQL, how can rewrite the query and let it work also in Microsoft SQL ?
The best would be that the same query can run without any changes in all these three database server : MySQL, PostgreSQL, MSSQL.
SQL Server doesn’t allow boolean expressions as you are trying here.
The following should work in all three.
Note that
CASEexpressions inWHEREclauses are completely unsargable