sql error on for xml removal - sql

Hi we have a legacy code which we are trying to modify and trying to get rid of "for XML". the current code is as below
Select
a.columnidfk as columnid,
tvs.columnversion as columnversion,
a.newcolumnId as newcolumnid,
(Select
at.columnTrackingId as columntrackingid,
at.newcolumnIdFk as newcolumnid,
at.IDBSIdFk as idbid,
i.Name as iname,
IsNull(convert(varchar,at.colidbdate,101),'') as colidbdate,
IsNull(convert(varchar,at.colidbdate2,101),'') as colidbdate2,
IsNull(at.colReason, '') as colReason,
IsNull(d.DispositionText, '') as DispositionText,
at.status as status
From columnTracking at
Left Outer Join LkIDBs i on at.IDBSIdFk = i.IDBSId
left outer join LkDisposition d On at.[colDecisionIdFk] = d.DispositionId
Where at.status in('Active','Inactive') and at.newcolumnIdFk = a.newcolumnId and (i.status in ('Active','Inactive') OR i.status is null) and (d.status='Active' or d.status is null)
for Xml path('columntracking'), type)
From tablecolumns a
Left Outer Join columnVersions tvs on a.columnversionidfk = tvs.columnversionid Where
a.columnVersionIdFk in
(Select columnVersionId From columnVersions tv
Inner Join tabcolumns t On tv.colIdFk = t.colId
Where t.TicketNo = #TicketNo )
order by a.TicketVersionIdFk , a.assessmentid
For Xml path('columntab'), Root('columns')
when i remove the "for Xml path('columntracking'), type" and "For Xml path('columntab'),Root('columns')" im getting the below error
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Please advise !

I believe i got the desired table out by Joining the (first xml out put)
Select
a.columnidfk as columnid,
tvs.columnversion as columnversion,
a.newcolumnId as newcolumnid,
att.columntrackingid,
att.newcolumnid,
att.idbid,
att.iname
From tablecolumns a
Left Outer Join columnVersions tvs on a.columnversionidfk = tvs.columnversionid Where
left outer join (
Select
at.columnTrackingId as columntrackingid,
at.newcolumnIdFk as newcolumnid,
at.IDBSIdFk as idbid,
i.Name as iname,
IsNull(convert(varchar,at.colidbdate,101),'') as colidbdate,
IsNull(convert(varchar,at.colidbdate2,101),'') as colidbdate2,
IsNull(at.colReason, '') as colReason,
IsNull(d.DispositionText, '') as DispositionText,
at.status as status
From columnTracking at
Left Outer Join LkIDBs i on at.IDBSIdFk = i.IDBSId
left outer join LkDisposition d On at.[colDecisionIdFk] = d.DispositionId
Where at.status in('Active','Inactive') and (i.status in ('Active','Inactive') OR i.status is null) and (d.status='Active' or d.status is null)
) att on att.newcolumnid = a.newcolumnId
and a.columnVersionIdFk in
(Select columnVersionId From columnVersions tv
Inner Join tabcolumns t On tv.colIdFk = t.colId
Where t.TicketNo = #TicketNo )

Related

Multi-part identifier could not be bound?

drop table #test1
/*** Master Validation Query!!!!!DO NOT CHANGE GROUPINGS!!!!**/
/**07/25/2007
1. Updated Discount code to link back to worktable
2. Updated U&C Calculation
3. Updated Non_covered calculation
*********************************************/
select
min(clm_net) as ProNet,
min(v1.val_opt) as opt,
min(clm_prod) as prod,
min(c.clm_drgc) as drgcode,
min(c.clm_4) as clm_4,
min(c.clm_cc2) as clm_cc2,
min(c.clm_cc3) as clm_cc3,
min(c.clm_3) as clm_3,
min(c.clm_38a) as clm_38a,
min(c.clm_38b) as clm_38b,
min(c.clm_12a) as clm_12a,
min(c.clm_12b) as clm_12b,
min(c.clm_60a) as clm_60a,
min(m.mem_altid) as AltId,
min(c.clm_5) as clm_5,
min(c.clm_1a1) as clm_1a1 ,
min(c.clm_1a2) as clm_1a2,
min(c.clm_deg) as clm_deg,
min(pro_spec1) as specialty,
min(v3.val_desc) as ProDesc1,
min(pro_xtyp) as protype,
min(c.clm_1a) as clm_1a,
min(c.clm_batch) as clm_batch,
min(c.clm_id1) as clm_id1,
min(s.clms_line) as clms_line,
min(s.clms_from) as clms_from,
min(s.clms_thru) as clms_thru,
impact.dbo.u_poscalc3(min(clm_form),min(clm_4),min(clms_rev),min(clm_spc),min(clms_pos),min(clms_ben),min(clm_67)) as clm_POS,
min(s.clms_rev) as clms_rev,
min(v6.val_desc) as procdesc2,
min(s.clms_proc) as clms_proc,
min(v4.val_desc) as procdesc,
min(s.clms_mod1) as clms_mod1,
min(v5.val_desc) as moddesc,
min(c.clm_67) as Diagnosis,
min(v1.val_desc) as Dcode,
min(v1.val_opt) as class,
min(v2.val_desc) as Dclass,
min(c.clm_68) as clm_68,
min(c.clm_69) as clm_69,
min(s.clms_chg) as clms_chg,
min(s.clms_sku) as clms_sku,
min(s.clms_allow) as clms_allow,
min(s.clms_copa) as clms_copa,
min(s.clms_dedu) as clms_dedu,
min(s.clms_coin) as clms_coin,
min(s.clms_non) as clms_non,
min(s.clms_cobp) as clms_cobp,
min(s.clms_wh) as clms_wh,
min(s.clms_payp) as clms_payp,
min(s.clms_paye) as clms_paye,
min(c.clm_inet) as clm_inet,
min(s.clms_ben) as clms_ben,
min(c.clm_form) as clm_form,
Min(c.clm_stades) as clm_stades,
min(c.clm_edid) as clm_edid,
Min(c.clm_chkno) as clm_chkno,
min(c.clm_dout) as clm_dout,
min(c.clm_chgdt) as clm_chgdt,
min(c.clm_ips) as clm_ips,
min(c.clm_den) as Den,
min(clm_pclm) as TXENnum,
min(d.clmd_cm01) as prindiag,
min(icd10.DIAG_CODE) as diagcode
into #test1
from impact.dbo.tbl_clm c
left join impact.dbo.tbl_mem m on m.mem_id1 = c.clm_12
left join impactwork.dbo.icd_diag_codes icd9 on icd9.diag_code = left(c.clm_67, 3) and icd9.code_type = 'ICD9_DIAG'
left join impactwork.dbo.icd_diag_codes icd10 on icd10.diag_code = left(d.clmd_cm01, 3) and icd10.code_type = 'ICD10_DIAG'
left join impact.dbo.tbl_clmd d on clmd_id1 = c.clm_id1
left join impact.dbo.tbl_meme e on e.meme_id1 = c.clm_12
left join impact.dbo.tbl_clms s on s.clms_id = c.clm_id1
left join impact.dbo.tbl_valid diag on diag.val_code = clm_67 and diag.val_type = '503'
left join tbl_valid v1 on v1.val_type = '57a'and v1.val_code = c.clm_67 --primary diagnosis
left join tbl_valid v2 on v2.val_type = '57b' and v2.val_code = v1.val_opt -- The val_opt of the code relates to the class
left join impact.dbo.tbl_pro p on c.clm_1 = p.pro_id1
left join tbl_valid v3 on v3.val_type = '302'and v3.val_code = pro_spec1
left join tbl_valid v4 on v4.val_type = '501' and v4.val_code = clms_proc
left join tbl_valid v5 on v5.val_type = '502' and v5.val_code = clms_mod1
left join tbl_valid v6 on v6.val_type = '506' and v6.val_code = clms_rev
where c.clm_stades = 'paid'
and c.clm_stades != 'dupl'
and clm_form != 'B'
and clms_Actn != 'Change'
and c.clm_prod !='den'
and c.clm_dout between '01/01/2015' and '05/31/2015'
and c.clm_prod <> 'flx'
and clm_cc2 in ('52037')
group by c.clm_id1,s.clms_line,c.clm_cc2
order by c.clm_Id1,s.clms_line,c.clm_cc2
select *
from #test1
I am getting an error:
on line 85 stating, 'The multi-part identifier "d.clmd_cm01" could
not be bound.
Why am I getting such an error? I looked to make sure that all of my aliases are used in the join, but that doesn't seem to be the problem.
You need to have the join:
left join impact.dbo.tbl_clmd d on clmd_id1 = c.clm_id1
before
left join impactwork.dbo.icd_diag_codes icd10 on icd10.diag_code = left(d.clmd_cm01, 3) and icd10.code_type = 'ICD10_DIAG'
As the above join uses a column from impact.dbo.tbl_clmd d as a join predicate.
This should work:
drop table #test1
/*** Master Validation Query!!!!!DO NOT CHANGE GROUPINGS!!!!**/
/**07/25/2007
1. Updated Discount code to link back to worktable
2. Updated U&C Calculation
3. Updated Non_covered calculation
*********************************************/
select
min(clm_net) as ProNet,
min(v1.val_opt) as opt,
min(clm_prod) as prod,
min(c.clm_drgc) as drgcode,
min(c.clm_4) as clm_4,
min(c.clm_cc2) as clm_cc2,
min(c.clm_cc3) as clm_cc3,
min(c.clm_3) as clm_3,
min(c.clm_38a) as clm_38a,
min(c.clm_38b) as clm_38b,
min(c.clm_12a) as clm_12a,
min(c.clm_12b) as clm_12b,
min(c.clm_60a) as clm_60a,
min(m.mem_altid) as AltId,
min(c.clm_5) as clm_5,
min(c.clm_1a1) as clm_1a1 ,
min(c.clm_1a2) as clm_1a2,
min(c.clm_deg) as clm_deg,
min(pro_spec1) as specialty,
min(v3.val_desc) as ProDesc1,
min(pro_xtyp) as protype,
min(c.clm_1a) as clm_1a,
min(c.clm_batch) as clm_batch,
min(c.clm_id1) as clm_id1,
min(s.clms_line) as clms_line,
min(s.clms_from) as clms_from,
min(s.clms_thru) as clms_thru,
impact.dbo.u_poscalc3(min(clm_form),min(clm_4),min(clms_rev),min(clm_spc),min(clms_pos),min(clms_ben),min(clm_67)) as clm_POS,
min(s.clms_rev) as clms_rev,
min(v6.val_desc) as procdesc2,
min(s.clms_proc) as clms_proc,
min(v4.val_desc) as procdesc,
min(s.clms_mod1) as clms_mod1,
min(v5.val_desc) as moddesc,
min(c.clm_67) as Diagnosis,
min(v1.val_desc) as Dcode,
min(v1.val_opt) as class,
min(v2.val_desc) as Dclass,
min(c.clm_68) as clm_68,
min(c.clm_69) as clm_69,
min(s.clms_chg) as clms_chg,
min(s.clms_sku) as clms_sku,
min(s.clms_allow) as clms_allow,
min(s.clms_copa) as clms_copa,
min(s.clms_dedu) as clms_dedu,
min(s.clms_coin) as clms_coin,
min(s.clms_non) as clms_non,
min(s.clms_cobp) as clms_cobp,
min(s.clms_wh) as clms_wh,
min(s.clms_payp) as clms_payp,
min(s.clms_paye) as clms_paye,
min(c.clm_inet) as clm_inet,
min(s.clms_ben) as clms_ben,
min(c.clm_form) as clm_form,
Min(c.clm_stades) as clm_stades,
min(c.clm_edid) as clm_edid,
Min(c.clm_chkno) as clm_chkno,
min(c.clm_dout) as clm_dout,
min(c.clm_chgdt) as clm_chgdt,
min(c.clm_ips) as clm_ips,
min(c.clm_den) as Den,
min(clm_pclm) as TXENnum,
min(d.clmd_cm01) as prindiag,
min(icd10.DIAG_CODE) as diagcode
into #test1
from impact.dbo.tbl_clm c
left join impact.dbo.tbl_mem m on m.mem_id1 = c.clm_12
left join impactwork.dbo.icd_diag_codes icd9 on icd9.diag_code = left(c.clm_67, 3) and icd9.code_type = 'ICD9_DIAG'
left join impact.dbo.tbl_clmd d on clmd_id1 = c.clm_id1
left join impactwork.dbo.icd_diag_codes icd10 on icd10.diag_code = left(d.clmd_cm01, 3) and icd10.code_type = 'ICD10_DIAG'
left join impact.dbo.tbl_meme e on e.meme_id1 = c.clm_12
left join impact.dbo.tbl_clms s on s.clms_id = c.clm_id1
left join impact.dbo.tbl_valid diag on diag.val_code = clm_67 and diag.val_type = '503'
left join tbl_valid v1 on v1.val_type = '57a'and v1.val_code = c.clm_67 --primary diagnosis
left join tbl_valid v2 on v2.val_type = '57b' and v2.val_code = v1.val_opt -- The val_opt of the code relates to the class
left join impact.dbo.tbl_pro p on c.clm_1 = p.pro_id1
left join tbl_valid v3 on v3.val_type = '302'and v3.val_code = pro_spec1
left join tbl_valid v4 on v4.val_type = '501' and v4.val_code = clms_proc
left join tbl_valid v5 on v5.val_type = '502' and v5.val_code = clms_mod1
left join tbl_valid v6 on v6.val_type = '506' and v6.val_code = clms_rev
where c.clm_stades = 'paid'
and c.clm_stades != 'dupl'
and clm_form != 'B'
and clms_Actn != 'Change'
and c.clm_prod !='den'
and c.clm_dout between '01/01/2015' and '05/31/2015'
and c.clm_prod <> 'flx'
and clm_cc2 in ('52037')
group by c.clm_id1,s.clms_line,c.clm_cc2
order by c.clm_Id1,s.clms_line,c.clm_cc2
select *
from #test1
Table impact.dbo.tbl_clmd is aliased as d (longer aliases FTW, helps readability). If you're seeing the error
'The multi-part identifier "d.clmd_cm01" could not be bound.
Then I'd be almost certain that table impact.dbo.tbl_clmd doesn't contain a column clmd_cm01.
EDIT - Kamran Farzami's spotted what I missed, that the table aliased in d is only joined in after it's been used as a join criteria. In any RDMBS I've used they have to be declared in order - you can't depend on what hasn't already been referenced in the query.

How can i do a conditional where clause in SQL, for missed back ups?

I have a pretty standard query for a back up aging report. What I want / need to do is have it report on missed back ups. I will need to see the last full database back up older than 2 days. I will also need to see any differential back ups older than the last day and any log back ups older than 30 mins. I'm not sure how to do the conditional where clause.
here's my basic query
SELECT
A.[Server],
A.database_name,
A.last_db_backup_date,
B.backup_type,
B.backup_start_date,
B.expiration_date,
B.backup_size,
B.logical_device_name,
B.physical_device_name,
B.backupset_name,
B.description
FROM
(
SELECT
CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server,
msdb.dbo.backupset.database_name,
MAX(msdb.dbo.backupset.backup_finish_date) AS last_db_backup_date
FROM msdb.dbo.backupmediafamily
INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id
GROUP BY
msdb.dbo.backupset.database_name
) AS A
LEFT JOIN
(
SELECT
CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server,
msdb.dbo.backupset.database_name,
msdb.dbo.backupset.backup_start_date,
msdb.dbo.backupset.backup_finish_date,
msdb.dbo.backupset.expiration_date,
msdb.dbo.backupset.backup_size,
msdb.dbo.backupmediafamily.logical_device_name,
msdb.dbo.backupmediafamily.physical_device_name,
msdb.dbo.backupset.name AS backupset_name,
msdb.dbo.backupset.description,
CASE msdb..backupset.type
WHEN 'D' THEN 'Full Database'
WHEN 'L' THEN 'Log'
WHEN 'I' THEN 'Differential'
WHEN 'F' THEN 'File Level'
WHEN 'G' THEN 'File Level Differential'
WHEN 'P' THEN 'Partial'
WHEN 'Q' THEN 'Differential partial'
END AS backup_type
FROM msdb.dbo.backupmediafamily
INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id
) AS B
ON A.[server] = B.[server] AND A.[database_name] = B.[database_name] AND A.[last_db_backup_date] = B.[backup_finish_date]
ORDER BY
A.database_name
Use a CASE statement. I'll paste an example from my own work:
SELECT
cplnt.complainant_type AS complainant_type,
cpt.date_received AS complaint_received,
CASE WHEN cpt.date_closed IS NULL
THEN (CURRENT_DATE - cpt.date_received)
ELSE (cpt.date_closed - cpt.date_received)
END AS complaint_age,
cpt.id AS complaint_id,
cs.date_case_received AS case_received,
cs.case_status AS case_stage,
stg.stage AS complaint_stage,
tm.name AS team,
trg.date_completed AS triage_date,
trg.method AS triage_method,
cpt.date_closed AS resolution_date,
cpt.status AS closure_type,
cpt.resolution_type AS resolution_type,
cpt.estimated_time_spent AS CLO_time_investment
FROM
complaints_complaint AS cpt
INNER JOIN
complaints_complainant AS cplnt
ON
cpt.complainant_id = cplnt.id
LEFT OUTER JOIN
complaints_case AS cs
ON
cpt.case_id = cs.id
INNER JOIN
complaints_stage AS stg
ON
cpt.stage_id = stg.id
INNER JOIN
community_team AS tm
ON
cpt.team_id = tm.id
LEFT OUTER JOIN
schemes_scheme AS sc
ON
cs.scheme_id = sc.id
LEFT OUTER JOIN
(SELECT
t1.*,
MIN(date_completed) OVER(PARTITION BY complaint_id) AS seq
FROM
complaints_triage AS t1) AS trg
ON
trg.complaint_id = cpt.id AND trg.date_completed = trg.seq;

what is this code doing can not understand it

I am trying to figure out what a query is doing and I just do not understand why it would join its self to its self on multiple occassions highlighted bit is the piece i am talking about?
its the part that starts with the [SupplyStatusUpdated] = COALESCE( gas supply and gas supply history
USE [CRM];
SELECT gs.GasSupplyID,
[Account ID] = acc.AccountID,
[GMSReference] = cast(gms.SiteRefNum as varchar),
[AccountNumber] = cast(gms.AccountNum as varchar),
[Organisation Name] = prf.[Name] ,
con.DeclaredDate,
[Contract Date] = CAST(con.ContractDate AS DATE),
[Contract Version] = cv.Name,
[Contract Status] = cs.Name,
loa.ContractEndDate [LOA CED],
gs.CurrentSupplierEndDate [PrevSupplierEndDate],
loa.ContractEndDate,
con.StartDate,
[Supply Status] = gss.Name,
[SupplyStatusUpdated] = COALESCE(
(
SELECT TOP 1 MAX(gsh2.CreatedDate)
FROM GasSupply gs2
INNER JOIN GasSupplyHistory gsh2
ON gsh2.GasSupplyFK = gs2.GasSupplyID
WHERE gsh2.EventFK = 2
AND gsh2.Notes LIKE '%Gas Supply Status (%'
AND gsh2.GasSupplyFK = gs.GasSupplyID
GROUP BY gsh2.GasSupplyFK
),
(
SELECT TOP 1 MAX(gsh3.CreatedDate)
FROM GasSupplyHistory gsh3
INNER JOIN (
SELECT gsh4.GasSupplyFK, MAX(gsh4.EventFK) AS [MaxEvent]
FROM GasSupplyHistory gsh4
WHERE gsh4.GasSupplyFK = gs.GasSupplyID
GROUP BY gsh4.GasSupplyFK
HAVING MAX(gsh4.EventFK) = 1
) dt
ON dt.GasSupplyFK = gsh3.GasSupplyFK
)
),
[EAC] = gs.EstimatedAnnualConsumption,
[PreviousSupplier] = r.name,
[Branch] = b.name,
[LeadSource] = ls.name,
gs.UnitPrice,
gs.StandingCharge,
gs.WholesalePrice,
COALESCE(deal.weeknumber,DATEPART(ISOWK, con.[ContractDate])) AS [Week]
FROM acc.Account acc
INNER JOIN [Profile] prf
ON acc.ProfileFK = prf.ProfileID
INNER JOIN [Contract] con
ON acc.AccountID = con.AccountFK
INNER JOIN [loacontract] lo
ON lo.ContractFK = con.ContractID
LEFT join [LeadSource] ls
ON ls.LeadSourceID = con.LeadSourceFK
INNER JOIN [ContractStatus] cs
ON cs.ContractStatusID = con.ContractStatusFK
INNER JOIN [ContractVersion] cv
ON cv.ContractVersionID = con.ContractVersionFK
INNER JOIN GasSupply gs
ON gs.ContractFK = con.ContractID
INNER JOIN GasSupplyStatus gss
ON gss.GasSupplyStatusID = gs.GasSupplyStatusFK
LEFT JOIN Deal deal
ON deal.ContractFK = con.ContractID
OUTER APPLY GetGMSReferenceNumbers(con.ContractID) gms
LEFT JOIN Branch b
ON b.BranchID = deal.BranchFK
LEFT JOIN DealBroker bro
ON bro.DealFK = deal.DealID
AND bro.BrokerTypeFK = 36
LEFT JOIN Person p
ON p.PersonID = bro.EmployeeFK
LEFT JOIN Reseller r
ON r.ResellerID = gs.ResellerFK
LEFT JOIN (
SELECT l.contractfk,
MIN(l.contractenddate)[ContractEndDate]
FROM CRM.[contract].LOAContract l
GROUP BY l.ContractFK
) loa
ON loa.ContractFK = con.ContractID
WHERE acc.AccountID not in (
select AccountFK
from AccountOption
where OptionFK=9
)
AND cast(gms.SiteRefNum as varchar) IS NULL
COALESCE(Something, SomethingElse) says if the first argument is NULL, return the second argument (note that you can have more than 2 args and it'll just keep going down the list).
As such it's running the first sub-query, and if the result is NULL, returning the result of the second query. Why exactly is your business logic, which we can't answer :-)
(MSDN link on Coalesce)
COALESCE returns the first non-null value it finds, so if the GasSupply query returns a result it will use that: if that returns null it will see if the GasSupplyHistory query returns a result, and if so use that. If both queries return null then SupplyStatusUpdated will be null.
It joins to itself to get historical records from the same source as where it gets the current record.
Representation of historical data is is one common reason for using a BigData/NoSQL database instead of a SQL/Relational database.

Query Performance too Slow

Im having performance issues with this query. If I remove the status column it runs very fast but adding the subquery in the column section delays way too much the query 1.02 min. How can I modify this query so it runs fast getting the desired data.
The reason I put that subquery there its because I needed the status for the latest activity, some activities have null status so I have to ignore them.
Establishments: 6.5k rows -
EstablishmentActivities: 70k rows -
Status: 2 (Active, Inactive)
SELECT DISTINCT
est.id,
est.trackingNumber,
est.NAME AS 'establishment',
actTypes.NAME AS 'activity',
(
SELECT stat3.NAME
FROM SACPAN_EstablishmentActivities eact3
INNER JOIN SACPAN_ActivityTypes at3
ON eact3.activityType_FK = at3.code
INNER JOIN SACPAN_Status stat3
ON stat3.id = at3.status_FK
WHERE eact3.establishment_FK = est.id
AND eact3.rowCreatedDT = (
SELECT MAX(est4.rowCreatedDT)
FROM SACPAN_EstablishmentActivities est4
INNER JOIN SACPAN_ActivityTypes at4
ON est4.establishment_fk = est.id
AND est4.activityType_FK = at4.code
WHERE est4.establishment_fk = est.id
AND at4.status_FK IS NOT NULL
)
AND at3.status_FK IS NOT NULL
) AS 'status',
est.authorizationNumber,
reg.NAME AS 'region',
mun.NAME AS 'municipality',
ISNULL(usr.NAME, '') + ISNULL(+ ' ' + usr.lastName, '')
AS 'created',
ISNULL(usr2.NAME, '') + ISNULL(+ ' ' + usr2.lastName, '')
AS 'updated',
est.rowCreatedDT,
est.rowUpdatedDT,
CASE WHEN est.rowUpdatedDT >= est.rowCreatedDT
THEN est.rowUpdatedDT
ELSE est.rowCreatedDT
END AS 'LatestCreatedOrModified'
FROM SACPAN_Establishments est
INNER JOIN SACPAN_EstablishmentActivities eact
ON est.id = eact.establishment_FK
INNER JOIN SACPAN_ActivityTypes actTypes
ON eact.activityType_FK = actTypes.code
INNER JOIN SACPAN_Regions reg
ON est.region_FK = reg.code --
INNER JOIN SACPAN_Municipalities mun
ON est.municipality_FK = mun.code
INNER JOIN SACPAN_ContactEstablishments ce
ON ce.establishment_FK = est.id
INNER JOIN SACPAN_Contacts con
ON ce.contact_FK = con.id
--JOIN SACPAN_Status stat ON stat.id = actTypes.status_FK
INNER JOIN SACPAN_Users usr
ON usr.id = est.rowCreatedBy_FK
LEFT JOIN SACPAN_Users usr2
ON usr2.id = est.rowUpdatedBy_FK
WHERE (con.ssn = #ssn OR #ssn = '*')
AND eact.rowCreatedDT = (
SELECT MAX(eact2.rowCreatedDT)
FROM SACPAN_EstablishmentActivities eact2
WHERE eact2.establishment_FK = est.id
)
--AND est.id = 6266
ORDER BY 'LatestCreatedOrModified' DESC
Try moving that 'activiy' query to a Left Join and see if it speeds it up.
I solved the problem by creating a temporary table and creating an index to it, this removed the need of the slow subquery in the select statement. Then I join the temp table as I do with normal tables.
Thanks to all.

SQL Server 'FOR XML PATH' in PHP/MySQL

I have a SQL Server query that I need to convert to MySQL. I've never used SQL Server/T-SQL before, so I have no experience with FOR XML PATH. There's surprisingly little documentation on this sort of thing. If I remove the FOR XML PATH statement, MySQL returns the error "Operand should contain at least 1 column(s)."
It seems like the nested SELECT statements return strings containing raw XML data, but I don't have the original SQL Server database available to test that theory. I could emulate this effect easily if I knew the return schema.
The original query is below:
SELECT
har_autos.*, har_automodels.Model, har_automodels.MakeID, har_automakes.Make, har_autotypes.AutoType,
(SELECT har_notes.*, har_notelinks.Value
FROM har_notes
JOIN har_notelinks on (har_notes.ID = har_notelinks.NoteID)
WHERE har_autos.ID = har_notelinks.AutoID AND har_notes.NoteTypeID = 1)
AS 'UserNotes',
(SELECT har_notes.*, har_notelinks.Value
FROM har_notes
JOIN har_notelinks on (har_notes.ID = har_notelinks.NoteID)
WHERE har_autos.ID = har_notelinks.AutoID AND har_notes.NoteTypeID = 2)
AS 'EngineeringNotes'
FROM har_autos
LEFT JOIN har_automodels ON (har_autos.ModelID = har_automodels.ID)
LEFT JOIN har_automakes ON (har_automodels.MakeID = har_automakes.ID)
LEFT JOIN har_autotypes ON (har_autos.AutoTypeID = har_autotypes.ID)
UPDATE:
I rebuilt the query in its entirety and it now returns "Not unique table/alias: 'har_automakes'."
SELECT
har_autos.*,
har_automodels.Model,
har_automodels.MakeID,
har_automakes.Make,
har_autotypes.AutoType,
(SELECT
har_notes.ID,
har_notes.NoteTypeID,
har_notes.Text001,
har_notelinks.Value,
har_notelinks.AutoID,
har_autos.ID
FROM
har_notes
INNER JOIN har_notelinks ON (har_notes.ID = har_notelinks.NoteID),
har_autos
WHERE har_autos.ID = har_notelinks.AutoID AND har_notes.NoteTypeID = 1)
AS UserNotes,
(SELECT
har_notes.ID,
har_notes.NoteTypeID,
har_notes.Text001,
har_notelinks.Value,
har_notelinks.AutoID,
har_autos.ID
FROM
har_notes
INNER JOIN har_notelinks ON (har_notes.ID = har_notelinks.NoteID), har_autos
WHERE har_autos.ID = har_notelinks.AutoID AND har_notes.NoteTypeID = 2)
AS EngineeringNotes
FROM
har_autos
LEFT OUTER JOIN har_automodels ON (har_autos.ModelID = har_automodels.ID)
LEFT OUTER JOIN har_autotypes ON (har_autos.AutoTypeID = har_autotypes.ID),
har_automakes
LEFT OUTER JOIN har_automakes ON (har_automakes.MakeID = har_automakes.ID)
WHERE
ID = 1
This is the original T-SQL query (really sorry about all of these):
SELECT a.*, mo.Model, mo.MakeID, ma.Make, at.AutoType,
(SELECT n.*, nl.Value
FROM dbo.Notes n
JOIN dbo.NoteLinks nl on (n.ID = nl.NoteID)
WHERE a.ID = nl.AutoID AND n.NoteTypeID = 1
FOR XML PATH('Note'), TYPE
) AS 'UserNotes',
(SELECT n.*, nl.Value
FROM dbo.Notes n
JOIN dbo.NoteLinks nl on (n.ID = nl.NoteID)
WHERE a.ID = nl.AutoID AND n.NoteTypeID = 2
FOR XML PATH('Note'), TYPE
) AS 'EngineeringNotes'
FROM dbo.Autos a
LEFT JOIN dbo.AutoModels mo ON (a.ModelID = mo.ID)
LEFT JOIN dbo.AutoMakes ma ON (mo.MakeID = ma.ID)
LEFT JOIN dbo.AutoTypes at ON (a.AutoTypeID = at.ID)
Little Documentation:
Using PATH Mode
Basic Syntax of the FOR XML Clause
Examples: Using PATH Mode
Constructing XML Using FOR XML
All of the above are from the following search: http://social.technet.microsoft.com/Search/en-US/?Refinement=129&Query=for+xml+path.