I have a query that uses the old style Oracle join syntax. I'm trying to convert this to T-SQL to reflect a data storage change.
My query is:
SELECT
client_name1,
personal_business_ind,
birth_date,
sex
FROM
client ce,
exclusions_endorsements ee
WHERE
ce.client_reference = :clientid
AND ee.fourth_insert( ) = ce.client_reference
AND ee.identification_code( ) = 'OCCP1'
ORDER BY
ee.run_date_last_trans DESC;
Could anyone please help?
I have tried the following query but it doesn't seem to produce the correct output on SQL Server:
SELECT
client_name1,
personal_business_ind,
birth_date,
sex
FROM
client ce,
RIGHT OUTER JOIN
[CLOAS].[EE_ExclusionsEndorsements] ee ON ee.fourth_insert = ce.client_reference AND ee.identification_code = 'OCCP1'
WHERE
ce.client_reference = @clientid
ORDER BY
ee.run_date_last_trans DESC;
CodePudding user response:
That's "old" Oracle outer join operator. For example:
SQL> select d.deptno, max(e.ename) ename
2 from dept d, emp e
3 where e.deptno ( ) = d.deptno
4 group by d.deptno
5 order by d.deptno;
DEPTNO ENAME
---------- ----------
10 MILLER
20 SMITH
30 WARD
40
You'd - instead - use
SQL> select d.deptno, max(e.ename) ename
2 from dept d left join emp e on e.deptno = d.deptno
3 group by d.deptno
4 order by d.deptno;
DEPTNO ENAME
---------- ----------
10 MILLER
20 SMITH
30 WARD
40
SQL>
Or, in your case,
SELECT
client_name1,
personal_business_ind,
birth_date,
sex
FROM exclusions_endorsements ee left join client ce on ee.fourth_insert = ce.client_reference
AND ee.identification_code = 'OCCP1'
WHERE
ce.client_reference = :clientid
ORDER BY
ee.run_date_last_trans DESC;
CodePudding user response:
You are close. But the outer joined table is exclusions_endorsements
, not client
, so you need a LEFT OUTER JOIN
. And there is a comma too many after FROM client ce
in your query.
One more point: Oracle sorts nulls first when ordering descendingly, SQL Server sorts them last. And SQL Server does not support standard SQL syntax NULLS FIRST
. We need a case expression hence.
SELECT
client_name1,
personal_business_ind,
birth_date,
sex
FROM client ce
LEFT OUTER JOIN exclusions_endorsements ee
ON ee.fourth_insert = ce.client_reference
AND ee.identification_code = 'OCCP1'
WHERE
ce.client_reference = @clientid
ORDER BY
CASE WHEN ee.run_date_last_trans IS NULL THEN 1 ELSE 2 END,
ee.run_date_last_trans DESC;
I should add that the query would look better, did you qualify all columns. E.g. ce.client_name1
. And sorting by a column you don't select can make the result look completely unordered. Well, maybe it's a non-nullable column, in that case it would just serve to get the outer-joined rows separated from the inner-joined rows in the result.