Related
I have taken over the support of an Excel 2010 macro and need to change the sort order of a recordset.
The query below worked before I attempted to change the order by adding rl.list_order.
Now I'm getting the error "The multi-part identifier could not be bound" and have tried many alternatives and have researched on this site for a solution but haven't been able to solve this. Can someone please help.
SELECT ips_rc.project, lfbe.Category, ips_rc.roster_id, ips_rc.role_category, ips_rc.role_title AS Role, ips_rc.role_code, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role, CASE WHEN ISNULL(lfbe.Pronto_Role_Code, '') = '' THEN 'TO_BE_MAPPED' ELSE ISNULL(lfbe.Pronto_Role_Code, '') END AS Pronto_Role_Code, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = '' THEN ips_rc.role_title ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '') END AS Pronto_Role_Code_Description, ISNULL(lfbe.Rate, 0) AS Rate, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = '' THEN ips_rc.role_title ELSE lfbe.Pronto_Role_Code_Old END AS Pronto_Role_Code_Old, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = '' THEN 'TO_BE_MAPPED' ELSE lfbe.Pronto_Role_Code_Description_Old END AS Pronto_Role_Code_Description_Old, ips_rc.Shift, ips_rc.UOM, ips_rc.Date, ips_rc.DHours, ips_rc.NHours FROM (SELECT psrc.project, pr_jcm.customer, pr_jcm.subcode, psrc.roster_id, psrc.role_id, psrc.role_category, psrc.role_title,
psrc.role_code, CASE WHEN SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.NWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.DWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) THEN 'Night Shifts' ELSE 'Day Shifts' END AS Shift, 'HOURS' AS UOM, psrc.Date, psrc.DHours, psrc.NHours FROM (SELECT rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id AS role_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END AS role_category, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END AS role_title, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_r
ole_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END AS role_code, rcd.shift_date AS Date, SUM(CASE WHEN rcd.shift_ampm = 'day' THEN rcd.shift_time ELSE 0 END) AS DHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS DWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS DEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS DEqdemobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' THEN rcd.shift_time ELSE 0 END) AS NHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS NWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS NEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.sh
ift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS NEqdemobHours FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_r
ole_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')) AS rb_test1 ON rb_test1.client_id = rcd.client_id AND rb_test1.role1_id = rcd.role1_id AND rb_test1.role2_id = rcd.role2_id AND rb_test1.role3_id = rcd.role3_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id '
)) AS rb_test2 ON rb_test2.client_id = rcd.client_id AND rb_test2.role1_id = rcd.role1_id AND rb_test2.role2_id = rcd.role2_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')) AS rb_test3 ON rb_test3.client_id = rcd.client_id AND rb_test3.role1_id = rcd.role1_id AND rb_test3.role3_id = rcd.role3_id WHERE rcd.shift_date > '2017-01-01' GROUP BY rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role
1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_role_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END, rcd.shift_date) AS psrc INNER JOIN (SELECT job_no AS project, Client AS customer, '3700002213' AS subcode FROM [dbo].[vw_PlanningSystem_Projects] WHERE job_no = '700704') AS pr_jcm ON pr_jcm.project = psrc.project) AS ips_rc LEFT OUTER JOIN (SELECT rates.Client, rates.SubCode, mapping.Category, mapping.Shift, mapping.IPS_Role_Code, rates.Pronto_Role_Code, rates.Pronto_Role_Code_Description, rates.Rate, rates.Pronto_Role_Code_Old, rates.Pronto_Role_Code_Description_Old FROM (SELECT UPPER(Ca
tegory) AS Category, 'Day Shifts' AS Shift, IPS_Role_Code, Day_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping] UNION ALL SELECT UPPER(Category) AS Category, 'Night Shifts' AS Shift, IPS_Role_Code, Night_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]) AS mapping INNER JOIN (SELECT Client, SubCode, CASE WHEN Shift = 'Day Shift' THEN 'Day Shifts' WHEN Shift = 'Night Shift' THEN 'Night Shifts' Else '' END AS Shift, Pronto_Role_Code, Pronto_Role_Code_Description, Rate, Pronto_Role_Code_Old, Pronto_Role_Code_Description_Old FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]) AS rates ON rates.Shift = mapping.Shift AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code) AS lfbe ON lfbe.Client = ips_rc.customer AND lfbe.SubCode = ips_rc.subCode AND lfbe.Shift = ips_rc.Shift AND lfbe.IPS_Role_Code = ips_rc.role_code ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, rl.list_order
Thanks for your help
Even with the formatting, you've got a lot going on here... Stack Overflow veterans, I'm just starting to dip my toes in here, so if this isn't correct, give me some grace.
In your first OPENQUERY statement, I don't see rl.list_order as a field being returned. If that's a column you're trying to ORDER BY, I think you should be able to add rl.list_order to your SELECT list within that statement which you alias as rcd.
Since that's within a nested sub-query, you'll want to elevate it to each of the calling queries. I think it's something like this... Try it out and post back with any errors.
SELECT ips_rc.ListOrder
, ips_rc.project
, lfbe.Category
, ips_rc.roster_id
, ips_rc.role_category
, ips_rc.role_title AS [ROLE]
, ips_rc.role_code
, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code, '') = ''
THEN 'TO_BE_MAPPED'
ELSE ISNULL(lfbe.Pronto_Role_Code, '')
END AS Pronto_Role_Code
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = ''
THEN ips_rc.role_title
ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '')
END AS Pronto_Role_Code_Description
, ISNULL(lfbe.Rate, 0) AS Rate
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = ''
THEN ips_rc.role_title
ELSE lfbe.Pronto_Role_Code_Old
END AS Pronto_Role_Code_Old
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = ''
THEN 'TO_BE_MAPPED'
ELSE lfbe.Pronto_Role_Code_Description_Old
END AS Pronto_Role_Code_Description_Old
, ips_rc.Shift
, ips_rc.UOM
, ips_rc.DATE
, ips_rc.DHours
, ips_rc.NHours
FROM (
SELECT psrc.ListOrder -- Added
, psrc.project
, pr_jcm.customer
, pr_jcm.subcode
, psrc.roster_id
, psrc.role_id
, psrc.role_category
, psrc.role_title
, psrc.role_code
, CASE
WHEN SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.NWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.DWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id)
THEN 'Night Shifts'
ELSE 'Day Shifts'
END AS Shift, 'HOURS' AS UOM, psrc.DATE, psrc.DHours, psrc.NHours
FROM (
SELECT rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id AS role_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END AS role_category
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END AS role_title
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END AS role_code, rcd.shift_date AS DATE
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
THEN rcd.shift_time
ELSE 0
END) AS DHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS DWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS DEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS DEqdemobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
THEN rcd.shift_time
ELSE 0
END) AS NHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS NWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS NEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS NEqdemobHours
FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl,ListOrder, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd --Added
LEFT JOIN (
SELECT client_id
, band_role_id
, title
, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category
, role1_id
, role2_id
, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')
) AS rb_test1
ON rb_test1.client_id = rcd.client_id
AND rb_test1.role1_id = rcd.role1_id
AND rb_test1.role2_id = rcd.role2_id
AND rb_test1.role3_id = rcd.role3_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role2_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id ')
) AS rb_test2
ON rb_test2.client_id = rcd.client_id
AND rb_test2.role1_id = rcd.role1_id
AND rb_test2.role2_id = rcd.role2_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')
) AS rb_test3
ON rb_test3.client_id = rcd.client_id
AND rb_test3.role1_id = rcd.role1_id
AND rb_test3.role3_id = rcd.role3_id
WHERE rcd.shift_date > '2017-01-01'
GROUP BY rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.ROLE1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END
, rcd.shift_date
) AS psrc
INNER JOIN (
SELECT job_no AS project
, Client AS customer
, '3700002213' AS subcode
FROM [dbo].[vw_PlanningSystem_Projects]
WHERE job_no = '700704'
) AS pr_jcm
ON pr_jcm.project = psrc.project
) AS ips_rc
LEFT JOIN (
SELECT rates.Client
, rates.SubCode
, mapping.Category
, mapping.Shift
, mapping.IPS_Role_Code
, rates.Pronto_Role_Code
, rates.Pronto_Role_Code_Description
, rates.Rate
, rates.Pronto_Role_Code_Old
, rates.Pronto_Role_Code_Description_Old
FROM (
SELECT UPPER(Category) AS Category
, 'Day Shifts' AS Shift
, IPS_Role_Code
, Day_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
UNION ALL
SELECT UPPER(Category) AS Category
, 'Night Shifts' AS Shift
, IPS_Role_Code
, Night_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
) AS mapping
INNER JOIN (
SELECT Client
, SubCode
, CASE
WHEN Shift = 'Day Shift'
THEN 'Day Shifts'
WHEN Shift = 'Night Shift'
THEN 'Night Shifts'
ELSE ''
END AS Shift
, Pronto_Role_Code
, Pronto_Role_Code_Description
, Rate
, Pronto_Role_Code_Old
, Pronto_Role_Code_Description_Old
FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]
) AS rates
ON rates.Shift = mapping.Shift
AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code
) AS lfbe
ON lfbe.Client = ips_rc.customer
AND lfbe.SubCode = ips_rc.subCode
AND lfbe.Shift = ips_rc.Shift
AND lfbe.IPS_Role_Code = ips_rc.role_code
ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, ips_rc.list_order ASC
You're right CSharp821 there's an awful lot going on there. I made the changes you suggested and it now works!
You are trying to access alias rl, however the rl alias is only visible within the OPENQUERY which has an alias of rcd. Try order by rcd.list_order instead of rl.list_order
I am working with a legacy system that only accepts dd/mm/yyyy in the XML for the data fields otherwise it mucks up the data entry.
I have tried every which way to attempt to force my data fields to display as dd/mm/yyyy, I have attempted to CONVERT to DATETIME 103, I have tried declaring it as a VARCHAR and everytime time it returns as 2018-05-11 for example.
How can I force the returned field to display as DD/MM/YYYY, this is a snippet of my code, excuse how messy it is unfortunately it is very linear and the system that accepts the XML is very basic.
SELECT TOP 1 1 'job/queue',
#Branch 'job/branch',
CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END 'parameters/yzt/char20.1',
SUBSTRING(#PolicyRef,1,6) 'broomsdata/broomsclient/bcm/refno',
#PolicyRef 'broomsdata/broomspolicy/bpy/refno',
CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END 'broomsdata/broomspolicy/myli/KEY',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Date1',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Code1',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Fine1',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Points1',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Date2',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Code2',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Fine2',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Points2',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Date3',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Code3',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Fine3',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Points3',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Date4',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Code4',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Fine4',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Points4'
FROM #ConvictionTable AS ct
LEFT OUTER JOIN [FIG-SQL-SRV].InfoCentre.dbo.ic_BD_MYLI AS myli ON ct.branch = myli.B# AND ct.policyRef = myli.PolRef#
FOR XML PATH('xmlexecute'), TYPE;
The Fields I'm trying to force are the 'Date1'/'Date2' etc. fields.
Cheers
Use CONVERT(varchar(10), YourDateColumn, 103). I think your mistake was trying to convert to a datetime (I'm guessing you tried CONVERT(datetime, YourDateColumn, 103)) while using a style code; date/time datatypes, in SQL Server, have no format. Trying to format them won't do anything.
For example: SELECT CONVERT(varchar(10), GETDATE(), 103); returns the varchar(10) value '11/05/2018'.
Edit: The below is to (temporary) assist the OP in showing how i create XML for OpenInterchange. The OP is using a lot of Sub Selects, something that doesn't help the speed of the query. I've highlighted, a couple of points for the OP to note as well:
SELECT K.Insco AS Insurer,
K.B# AS Branch,
K.PolRef# AS PolicyRef,
K.ClaimRef# AS ClaimRef,
--XML Generation starts here.
(SELECT(SELECT K.B# AS branch,
'OO' AS operator,
'PDF' AS printtype
FOR XML PATH('job'),TYPE),
(SELECT (SELECT 'update-claim' AS [Char20.1]
FOR XML PATH('yzt'),TYPE)
FOR XML PATH('parameters'),TYPE),
(SELECT (SELECT (SELECT K.Ref# AS Refno
FOR XML PATH('bcm'),TYPE)
FOR XML PATH('broomsclient'),TYPE),
(SELECT (SELECT K.PolRef# AS Refno
FOR XML PATH('bpy'),TYPE)
FOR XML PATH('broomspolicy'),TYPE),
(SELECT (SELECT K.ClaimRef# AS [Claim.No],
K.[Claim No] AS [Ins.Claim.Ref],
K.KGMSettled AS [Claim.Settled],
K.KGMReserve AS [Claim.Reserve],
K.KGMReserve + K.KGMSettled As [Claim.Amount],
K.KGMStatus AS [Stat.Desc],
CASE K.KGMStatus WHEN 'Settled' THEN 'SETT'
WHEN 'Ouststanding' THEN 'OUTS'
WHEN 'Declined' THEN 'DECL'
WHEN 'Not Taken up' THEN 'NTUP'
WHEN 'Withdrawn' THEN 'WITH' END AS [stat.code],
CONVERT(varchar(10),K.[Notified Date],103) AS [Date.repd], --First example of the dd/MM/yyyy format
CONVERT(varchar(10),K.[Loss Date],103) AS [Loss.date], --Another example of the dd/MM/yyyy format
CASE WHEN K.[Date Closed] IS NOT NULL THEN CONVERT(varchar(10), GETDATE(), 103) END AS [Stat.date], -- and another example of the dd/MM/yyyy format
CONVERT(varchar(10),K.[Date Closed],103) AS [Date.Settled], --you get the idea. :)
CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.[Date Closed] IS NULL THEN ''
WHEN K.[NCB Decision] = 'Allowed' THEN 'Yes'
WHEN K.[NCB Decision] = 'Disallowed' THEN 'Yes' END AS [Settled.free]
/*
CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.KGMReserve + K.KGMSettled = 0 AND K.[Date Closed] IS NOT NULL THEN 'Yes'
WHEN K.KGMReserve + K.KGMSettled > 0 AND K.[Date Closed] IS NOT NULL THEN 'No'
ELSE '' END AS [Settled.free]*/
FOR XML PATH('bch'),TYPE),
(SELECT K.BCAKey AS [KEY],
K.[Vehicle Reg# No] AS [Reg.no],
K.[Driver Name] AS [Driver],
K.[ AD Paid] AS [Pay.ad],
K.[AD Reserve] AS [Reserve.ad],
K.[TPD Paid] + K.[TPI Paid] AS [Pay.tp],
K.[TPD Reserve] + K.[TPI Reserve] AS [Reserve.tp],
--K.[TPI Paid] AS [Pay.others],
--K.[TPI Reserve] AS [Reserve.others],
0 AS [Pay.others],
0 AS [Reserve.others],
K.KGMSettled AS [Pay.total],
K.KGMReserve AS [Reserve.Total],
K.[Recovery] AS [Pay.recovs],
K.[AD Recovery Reserve] AS [Reserve.recovs],
'Updated by FileDrop Service. XML Generated on ' + CONVERT(varchar(10),GETDATE(),103) as [Remarks4]
FOR XML PATH('bca'),TYPE),
(SELECT CONVERT(varchar(10),GETDATE(),103) AS [date],
LEFT(CONVERT(varchar(10),GETDATE(),108),5) AS [time],
'OO' AS [op],
'FileDrop' AS [Name],
K.KGMSettled AS [Settled],
K.KGMReserve AS [Reserve],
K.KGMSettled + K.KGMReserve As [Total],
--CONVERT(varchar(10),K.DataToDate,103) AS [EffDate],
CASE WHEN K.KGMSettled != K.BCHSettled THEN 'Payment'
WHEN K.KGMReserve != K.BCHReserve THEN 'Reserve Adjustment'
ELSE 'Payment' END AS [Notes]
FOR XML PATH('clam'),TYPE)
FOR XML PATH('broomsclaim'),TYPE)
FOR XML PATH('broomsdata'),TYPE)
FOR XML PATH('xmlexecute'),TYPE) AS InputXML,
GETDATE() AS DateGenerated,
0 AS TestLoad
FROM KGMCGStandard_viw K
WHERE K.ClaimsFound = 1
AND K.KGMFound = 1
AND (K.KGMSettled != K.BCHSettled
OR K.KGMReserve != K.BCHReserve
OR (CONVERT(date,K.KGMClosure) != CONVERT(date,BCHClosure)
OR (K.KGMClosure IS NULL AND K.BCHClosure IS NOT NULL)
OR (K.KGMClosure IS NOT NULL AND K.BCHClosure IS NULL))
OR (CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.[NCB Decision] = 'Allowed' THEN 'Yes'
WHEN K.[NCB Decision] = 'Disallowed' THEN 'No' END != K.Settled_Free
OR (K.[Date Closed] IS NULL AND K.Settled_free IS NULL)))
AND NOT EXISTS (SELECT 1
FROM AutoloadXML_tbl A
WHERE A.Branch = K.B#
AND A.PolicyRef = K.PolRef#
AND A.ClaimRef = K.ClaimRef#
AND (A.DateSubmitted IS NULL
OR A.Installed = 0))
ORDER BY K.ClaimRef# ASC;
Since you already figured out the date part I will leave that up to you but your query could be simplified majorly using conditional aggregation. I used square braces around the column names instead of single quotes. Sure those work but I consider that a bad habit because it is difficult to decide if it is a string literal or a column alias. I also prefer to use alias = but that is more a preference thing. I also prefer leading commas which is also a preference thing.
Pretty sure this query should do the same thing.
SELECT 1 as 'job/queue',
#Branch as 'job/branch',
CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END as 'parameters/yzt/char20.1',
SUBSTRING(#PolicyRef,1,6) as 'broomsdata/broomsclient/bcm/refno',
#PolicyRef as 'broomsdata/broomspolicy/bpy/refno',
CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END as 'broomsdata/broomspolicy/myli/KEY'
, [broomsdata/broomspolicy/myli/Date1] = max(case when ct.RowNo = 1 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code1] = max(case when ct.RowNo = 1 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine1] = max(case when ct.RowNo = 1 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points1] = max(case when ct.RowNo = 1 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date2] = max(case when ct.RowNo = 2 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code2] = max(case when ct.RowNo = 2 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine2] = max(case when ct.RowNo = 2 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points] = max(case when ct.RowNo = 2 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date3] = max(case when ct.RowNo = 3 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code3] = max(case when ct.RowNo = 3 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine3] = max(case when ct.RowNo = 3 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points3] = max(case when ct.RowNo = 3 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date4] = max(case when ct.RowNo = 4 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code4] = max(case when ct.RowNo = 4 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine4] = max(case when ct.RowNo = 4 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points4] = max(case when ct.RowNo = 4 then ct.noofpoints end)
FROM #ConvictionTable AS ct
LEFT OUTER JOIN [FIG-SQL-SRV].InfoCentre.dbo.ic_BD_MYLI AS myli ON ct.branch = myli.B# AND ct.policyRef = myli.PolRef#
GROUP BY #Branch
, CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END
, SUBSTRING(#PolicyRef,1,6)
, #PolicyRef
, CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END
FOR XML PATH('xmlexecute'), TYPE
I am using SQL Server 2008. I am attempting to write a select statement using STUFF and FOR XML PATH to create a comma separated string in one field. There is only ONE record but 31 fields.
I'm pulling the data from 1 table which has a smallint field for each day of the month - 0 means no for that day, 1 means yes. (I did not design this table and unfortunately I am not allowed to change it.) Like so:
z1st z2nd z3rd z4th z5th z6th z7th z8th z9th z10th
------ ------ ------ ------ ------ ------ ------ ------ ------ ------
0 1 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 1
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 1
And so on, all the way through z31st.
My statement is passing integer variables #order_snbr and #admin_nbr, which will always return a single row.
DECLARE #strSelectedDayList AS VARCHAR(MAX)
SELECT #strSelectedDayList = STUFF((SELECT ', ' + CASE WHEN td1.z1st = 1 THEN '1st' END
, CASE WHEN td1.z2nd = 1 THEN '2nd' END
, CASE WHEN td1.z3rd = 1 THEN '3rd' END
, CASE WHEN td1.z4th = 1 THEN '4th' END
, CASE WHEN td1.z5th = 1 THEN '5th' END
, CASE WHEN td1.z6th = 1 THEN '6th' END
, CASE WHEN td1.z7th = 1 THEN '7th' END
, CASE WHEN td1.z8th = 1 THEN '8th' END
, CASE WHEN td1.z9th = 1 THEN '9th' END
, CASE WHEN td1.z10th = 1 THEN '10th' END
, CASE WHEN td1.z11th = 1 THEN '11th' END
, CASE WHEN td1.z12th = 1 THEN '12th' END
, CASE WHEN td1.z13th = 1 THEN '13th' END
, CASE WHEN td1.z14th = 1 THEN '14th' END
, CASE WHEN td1.z15th = 1 THEN '15th' END
, CASE WHEN td1.z16th = 1 THEN '16th' END
, CASE WHEN td1.z17th = 1 THEN '17th' END
, CASE WHEN td1.z18th = 1 THEN '18th' END
, CASE WHEN td1.z19th = 1 THEN '19th' END
, CASE WHEN td1.z20th = 1 THEN '20th' END
, CASE WHEN td1.z21st = 1 THEN '21st' END
, CASE WHEN td1.z22nd = 1 THEN '22nd' END
, CASE WHEN td1.z23rd = 1 THEN '23rd' END
, CASE WHEN td1.z24th = 1 THEN '24th' END
, CASE WHEN td1.z25th = 1 THEN '25th' END
, CASE WHEN td1.z26th = 1 THEN '26th' END
, CASE WHEN td1.z27th = 1 THEN '27th' END
, CASE WHEN td1.z28th = 1 THEN '28th' END
, CASE WHEN td1.z29th = 1 THEN '29th' END
, CASE WHEN td1.z30th = 1 THEN '30th' END
, CASE WHEN td1.z31st = 1 THEN '31st' END
FROM TableDays td1 WITH(NOLOCK)
WHERE td1.order_snbr = td2.order_snbr
AND td1.admin_nbr = td2.admin_nbr
FOR XML PATH('')), 1, 1, '')
FROM TableDays td2 WITH(NOLOCK)
WHERE td2.order_snbr = #order_snbr
AND td2.admin_nbr = #admin_nbr
PRINT #strSelectedDayList
This produces a result like so:
1st14th28th
What I would like is this:
1st, 14th, 28th
Any help would be much appreciated! And if there's a better way to do this (without STUFF or FOR XML PATH) I'm happy to switch.
Perhaps a another approach
Example
Declare #YourTable Table ([z1st] varchar(50),[z2nd] varchar(50),[z3rd] varchar(50),[z4th] varchar(50),[z5th] varchar(50),[z6th] varchar(50),[z7th] varchar(50),[z8th] varchar(50),[z9th] varchar(50))
Insert Into #YourTable Values
(0,1,0,0,0,1,0,0,0)
,(0,0,0,0,1,0,0,1,0)
,(0,0,1,0,0,0,0,0,0)
,(1,1,1,1,0,0,0,0,0)
,(0,1,0,0,0,0,1,0,1)
Select A.*
,C.*
From #YourTable A
Cross Apply (Select XMLData = cast((select A.* for XML Raw) as xml) ) B
Cross Apply (
Select S = Stuff((Select ', ' +replace(Item,'z','')
From (
Select Item = attr.value('local-name(.)','varchar(100)')
From B.XMLData.nodes('/row') as A(r)
Cross Apply A.r.nodes('./#*') AS B(attr)
Where attr.value('local-name(.)','varchar(100)') like 'z[0-9]%'
and attr.value('.','varchar(max)') =1
) C1
For XML Path ('')),1,2,'')
) C
Returns
I am trying to update one of my datasets in SSRS, and I am receiving the following error
"Could not update a list of fields for the query. Verify that you can connect to the data source and that your query syntax is correct"
My query is:
`SELECT eg.Name AS PropertyGroupName
, CASE ec.RAG WHEN 0 THEN 'Green' WHEN 1 THEN 'Amber' ELSE 'Red' END AS RAGColor
, CASE ec.RAG WHEN 0 THEN 'Green' WHEN 1 THEN 'Gold' ELSE 'Red' END AS RAGDisplayColor
, en.PropertyReference
, en.Name
, en.Address1
, en.Address2
, en.Address3
, en.Address4
, en.PostCode
, ec.ComplianceType AS [Compliance Type]
, ec.NextEventDate
, ec.RAG
, ec.Notes AS ComplianceDetail
FROM tEntityCompliance AS ec
INNER JOIN tEntity AS en ON en.ID = ec.EntityID
INNER JOIN tEntityGroupEntity AS ege ON ege.EntityID = en.ID
INNER JOIN tEntityGroup AS eg ON eg.ID = ege.EntityGroupID
WHERE (ec.CompanyID = #CompanyID)
AND (en.CompanyID = #CompanyID)
AND (eg.CompanyID = #CompanyID)
AND (en.Deleted = 0)
AND (en.Status = 1)
AND (eg.Name <> 'All properties')
AND (ec.ComplianceType IN (#ComplianceTypeFilter))
AND (eg.ID IN (#PropertyGroupNames))
AND (ec.RAG <> 0)'
I have this massive query that I can typically run in under 2 minutes. However, when I run it a second time about a minute after, it goes on infinitely... so I kill the process and my SSMS session. I don't have any other jobs running in the background.
Is something else being retained on the server? I think I'm missing something as far as how SQL Server works.
Thanks.
EDIT: Here's the SQL (had to do a little obfuscation)
SELECT pl.OrangeLocationID ,
e.EventID ,
cr.Title AS [Event Type] ,
su.LastName + ', ' + su.FirstName AS FMR ,
CONVERT(VARCHAR(20), pl.Report_Date, 101) AS [Report Entry Date] ,
l.Name ,
l.Number ,
ll.SodaPopLocationID AS [SodaPop Location ID] ,
l.Zip ,
c.Channel ,
pl.DT AS [ReportedDate] ,
RIGHT(pl.DT_start, 8) AS [ReportedStartTime] ,
RIGHT(pl.DT_end, 8) AS [ReportedEndTime] ,
[CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) AS [ReportedDuration] ,
pl.scheduled_date AS [ScheduledDate] ,
RIGHT(pl.scheduled_start, 8) AS [ScheduledStartTime] ,
RIGHT(pl.scheduled_end, 8) AS [ScheduledEndTime] ,
[CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) AS [ScheduledDuration] ,
e.HoursPaid AS [Rep Hours Worked] ,
ISNULL(PP.[RepCount], 0) AS [RepCount] ,
CASE WHEN [CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.DT_start, pl.DT_end)
WHEN [CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.scheduled_start, pl.DT_end)
ELSE ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
END AS [FinalDuration] ,
g.[Description] AS [OA Market] ,
g.SodaPop_Region AS [SodaPop Region] ,
g.SodaPop_Area AS [SodaPop Area] ,
coup4 ,
coupo ,
coupo_e ,
card_num ,
promo ,
promo_no ,
promo_no_o ,
highlight1 ,
highlight2 ,
highlight3 ,
mgmt_reaction ,
mgmt_reaction_e ,
comm_p ,
comm_n ,
r.comments ,
s_fname ,
s_lname ,
v_title ,
ll.KeyAccountCorp AS [Key Account Corp.] ,
interact_new + interact_rep AS [interact_total] ,
samp_new + samp_rep AS [samp_total] ,
purch_new + purch_rep AS [purch_total] ,
23 / ( NULLIF(( interact_new + interact_rep ), 0) * 1.0 ) AS [Int_Crate] ,
CASE WHEN sampletype = 11 THEN ( purch_new + purch_rep ) / ( NULLIF(( samp_new + samp_rep ), 0) * 1.0 )
ELSE NULL
END AS [Samp_Crate] ,
coup1 + coup2 AS [coup_total] ,
CASE WHEN coup1 + coupo > 0 THEN 1
ELSE 0
END AS [CoupDist] ,
DATEPART(month, pl.DT) AS [Visit_Month] ,
DATEPART(quarter, pl.DT) AS [Quarter] ,
DATEPART(weekday, pl.DT) AS [Weekday] ,
CASE DATEPART(weekday, pl.DT)
WHEN 6 THEN 'Fri'
WHEN 7 THEN 'Sat'
WHEN 1 THEN 'Sun'
ELSE 'Mon-Thurs'
END AS [Weekday_Grouped] ,
CASE WHEN dbo.Exception(pl.OrangeLocationID, 12) = 1
OR dbo.Exception(pl.OrangeLocationID, 13) = 1
OR dbo.Exception(pl.OrangeLocationID, 14) = 1 THEN 1
ELSE 0
END AS [EVolume] ,
CASE WHEN dbo.DoesHaveException(pl.OrangeLocationID, 18) = 1 THEN 1
ELSE 0
END AS [CVolume] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 9) = 1
OR dbo.eException(pl.OrangeLocationID, 22) = 1 THEN 1
ELSE 0
END AS [Volumes] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 8) = 1
OR dbo.eException(pl.OrangeLocationID, 21) = 1 THEN 1
ELSE 0
END AS [Sales Price] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 11) = 1 THEN 1
ELSE 0
END AS [Sample Volume] ,
ISNULL(i.[NormalizedSold], 0) AS [EQBottlesSold] ,
CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END AS [EQBottlesSoldPerPurch] ,
ac.AvgSales ,
ac.STDEVSales ,
( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales AS [sl] ,
ac.AvgPurchasers ,
ac.STDEVPurchasers ,
( ISNULL(r.purch_new, 0) - ac.AvgPurchasers ) / ac.STrchasers AS [ZScore_Purchasers] ,
ac.AvgConversions ,
ac.STDEVConversions ,
( ISNULL(( purch_new + purch_rep ) / ( NULLIF(( interact_new ), 0) ), 0) - ac.AvgConversions )
/ ac.STDEVConversions AS [ZScore_Conversions] ,
ac.[AvgSalesPerPurchaser] ,
ac.[STDEVSalesPerPurchaser] ,
( ISNULL(( CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser] ) / ac.[STDEVSalesPerPurchaser] AS [SalesPerPurchaser] ,
( ( ( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales )
+ ( (ISNULL(( CASE WHEN ISNULL(purch_new + purch_rep, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser]) ) ) / 4 AS [core] ,
( ( (( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales) ) / 4 ) + 3 AS [core] ,
su.aaUserID ,
l.LsocationID
FROM [CMS_SodaPop].dbo.Schedule pl WITH ( NOLOCK )
INNER JOIN [CMS_SodaPop].dbo.Report r WITH ( NOLOCK ) ON r.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS].dbo.Users su WITH ( NOLOCK ) ON su.UserID = pl.Rep_FMR
INNER JOIN [CMS].dbo.Locations l WITH ( NOLOCK ) ON l.LocationID = pl.LocationID
INNER JOIN [CMS].dbo.OrangeReports cr WITH ( NOLOCK ) ON cr.RedID = pl.RedID
INNER JOIN [CMS_SodaPop].dbo.Events e WITH ( NOLOCK ) ON e.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS_SodaPop].dbo.MarketList g WITH ( NOLOCK ) ON g.GroupID = pl.GroupID
INNER JOIN [CMS_SodaPop].dbo.Locations ll WITH ( NOLOCK ) ON ll.LocationID = pl.LocationID
LEFT JOIN [CMS_SodaPop].dbo.Channels c WITH ( NOLOCK ) ON ll.ChannelID = c.ChannelID
LEFT JOIN ( SELECT PLocationID ,
COUNT(DISTINCT UserID) AS [RepCount]
FROM [CMS_roll].dbo.rollItems WITH ( NOLOCK )
WHERE RedID = 154
GROUP BY OrangeLocationID
) PP ON PP.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN ( SELECT OrangeLocationID ,
SUM(NormalizedSold) AS [NormalizedSold]
FROM [Analysis].dbo.[vSodaPop_Retail_Inventory] WITH ( NOLOCK )
GROUP BY OrangeLocationID
) i ON i.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN [Analysis].dbo.[vSodaPop_Calculations] ac WITH ( NOLOCK ) ON ac.[Quarter] = CASE WHEN DATEPART(MM,
[DT]) IN ( 10,
11, 12 ) THEN 4
END
AND ac.[Year] = DATEPART(YY, pl.DT)
WHERE pl.Activity = 1
AND pl.RedID = 154
AND pl.GroupID <> 444
AND pl.[DT] < GETDATE()
AND DATEPART(YY, [DT]) >= 2010
AND ISNULL(i.NormalizedSold, 0) >= 0
AND DATEPART(year, GETDATE()) = DATEPART(year, r.Insert_Date)
Would have to see the query to really dig in however..
you could try adding OPTION (RECOMPILE) to the end of the query to force it to create a new execution plan.
Are you using Temp Tables?
Cursors not deallocated & closed?
You can look at Profiler to see if anything looks different between the 2 executions.
Are you sure it isn't being blocked by another process the second time?
What happens if you execute
CHECKPOINT;
GO;
DBCC DROPCLEANBUFFERS;
GO;
DBCC FREEPROCCACHE;
GO;
between the queries? This is not really a solution but will help diagnosis.