Need advice. The following changes causes my stored procedure to EXECUTE for 5mins - sql

I have the following view:
ALTER VIEW [dbo].[vAccount]
AS
with cte_accounts_data AS
(
SELECT
null as CompanyVendorAccountId
,CAST(0 as bit) as IsVendorAccount
,null as VendorAccountReference
,null as VendorCompanyId
,a.[AccountId]
,a.[CompanyId]
,a.[CompanyAccountTypeId]
,ag.[CompanyAccountGroupId]
,ag.[Name] as CompanyAccountGroupName
,a.[RegionId]
,a.[Name]
,CONCAT(c.ShortName + ': ', a.[Name], ' [' + a.[Code] +']') AS DisplayName
,a.[Code]
,a.[Address]
,a.[Email]
,a.[IncludeEscalationEmail]
,a.[GPSLat]
,a.[GPSLong]
,a.[Telephone]
,a.[VATNumber]
,a.[AutoReceive]
,a.[AutoIssue]
,a.[IsBillableToAccount]
,a.[BillingStart]
,a.[IsEquipmentDepot]
,a.[IsShiftAttendanceEnabled]
,a.[ShiftMinHoursForLunchDeduction]
,a.[NightShiftStart]
,a.[NightShiftEnd]
,a.[ShiftStartDayOfMonth]
,a.[OperatingHoursStart]
,a.[OperatingHoursEnd]
,a.[LoadBays]
,a.[LoadInterval]
,a.[ArrivalInterval]
,a.[OverrideStockTakeCloseBalanceTime]
--,a.[RFEquipment]
,a.[temp_IgnoreVendorIssueViaSAP]
,a.[Archived]
,a.[CreatedDate]
,a.[CreatedBy_PersonId]
,a.[UpdatedDate]
,a.[UpdatedBy_PersonId]
,cat.Name as CompanyAccountTypeName
,at.Name as AccountTypeName
,at.AccountTypeId
,at.EnumAccountType
,r.Name as Region
,c.Name as Company
,CONCAT(c.Code, ': ', a.Name, ' ',a.Code, ' ', c.Name, ' ', r.Name, ' ', at.Name, ' ', r.Code, ' ') as ViewSearchColumn
FROM
[Account] a
JOIN Company c on (a.CompanyId = c.CompanyId)
JOIN CompanyAccountType cat on (a.CompanyAccountTypeId = cat.CompanyAccountTypeId)
JOIN AccountType at on (cat.AccountTypeId = at.AccountTypeId)
LEFT OUTER JOIN vCompanyAccountGroup ag on (a.CompanyAccountGroupId = ag.CompanyAccountGroupId)
LEFT OUTER JOIN Region r on (a.RegionId = r.RegionId)
UNION
SELECT
cv.[CompanyVendorAccountId]
,CAST(1 as bit) as IsVendorAccount
,cv.[VendorAccountReference]
,a.[CompanyId] as VendorCompanyId
,a.[AccountId]
,cv.[CompanyId]
,cv.[CompanyAccountTypeId]
,ag.[CompanyAccountGroupId]
,ag.[Name] as CompanyAccountGroupName
,a.[RegionId]
,a.[Name]
,CONCAT(c.ShortName + ': ', a.[Name], ' [' + cv.[VendorAccountReference] +']') AS DisplayName
,cv.[VendorAccountReference] as [Code]
,a.[Address]
,a.[Email]
,a.[IncludeEscalationEmail]
,a.[GPSLat]
,a.[GPSLong]
,a.[Telephone]
,a.[VATNumber]
,a.[AutoReceive]
,a.[AutoIssue]
,a.[IsBillableToAccount]
,a.[BillingStart]
,a.[IsEquipmentDepot]
,a.[IsShiftAttendanceEnabled]
,a.[ShiftMinHoursForLunchDeduction]
,a.[NightShiftStart]
,a.[NightShiftEnd]
,a.[ShiftStartDayOfMonth]
,a.[OperatingHoursStart]
,a.[OperatingHoursEnd]
,a.[LoadBays]
,a.[LoadInterval]
,a.[ArrivalInterval]
,a.[OverrideStockTakeCloseBalanceTime]
--,a.[RFEquipment]
,a.[temp_IgnoreVendorIssueViaSAP]
,cv.[Archived]
,cv.[CreatedDate]
,cv.[CreatedBy_PersonId]
,cv.[UpdatedDate]
,cv.[UpdatedBy_PersonId]
,cat.Name as CompanyAccountTypeName
,at.Name as AccountTypeName
,at.AccountTypeId
,at.EnumAccountType
,r.Name as Region
,c.Name as Company
,CONCAT(c.Code, ': ', a.Name, ' ',a.Code, ' ', c.Name, ' ', r.Name, ' ', at.Name, ' ', r.Code, ' ') as ViewSearchColumn
FROM
[CompanyVendorAccount] cv
JOIN Company c on (cv.CompanyId = c.CompanyId)
JOIN CompanyAccountType cat on (cv.CompanyAccountTypeId = cat.CompanyAccountTypeId)
JOIN AccountType at on (cat.AccountTypeId = at.AccountTypeId)
JOIN Account a on (cv.VendorAccountId = a.AccountId)
LEFT OUTER JOIN Region r on (a.RegionId = r.RegionId)
LEFT OUTER JOIN vCompanyAccountGroup ag on (cv.CompanyAccountGroupId = ag.CompanyAccountGroupId)
WHERE
cv.CompanyId != a.CompanyId
)
,cte_ranking_order as
(
SELECT ROW_NUMBER() over (ORDER BY AccountId, CompanyId) as rankNumber,* FROM cte_accounts_data
)
SELECT [CompanyVendorAccountId]
,IsVendorAccount
,[VendorAccountReference]
,[VendorCompanyId]
,[AccountId]
,[CompanyId]
,[CompanyAccountTypeId]
,[CompanyAccountGroupId]
,[CompanyAccountGroupName]
,[RegionId]
,[Name]
,[DisplayName]
,[Code]
,[Address]
,[Email]
,[IncludeEscalationEmail]
,[GPSLat]
,[GPSLong]
,[Telephone]
,[VATNumber]
,[AutoReceive]
,[AutoIssue]
,[IsBillableToAccount]
,[BillingStart]
,[IsEquipmentDepot]
,[IsShiftAttendanceEnabled]
,[ShiftMinHoursForLunchDeduction]
,[NightShiftStart]
,[NightShiftEnd]
,[ShiftStartDayOfMonth]
,[OperatingHoursStart]
,[OperatingHoursEnd]
,[LoadBays]
,[LoadInterval]
,[ArrivalInterval]
,[OverrideStockTakeCloseBalanceTime]
,[temp_IgnoreVendorIssueViaSAP]
,[Archived]
,[CreatedDate]
,[CreatedBy_PersonId]
,[UpdatedDate]
,[UpdatedBy_PersonId]
,[CompanyAccountTypeName]
,[AccountTypeName]
,[AccountTypeId]
,[EnumAccountType]
,[Region]
,[Company]
,[ViewSearchColumn]
FROM cte_ranking_order where rankNumber = 1
GO
Which I modified to look like the above.
Below is the original View:
ALTER VIEW [dbo].[vAccount]
AS
with cte_accounts_data AS
(
SELECT
null as CompanyVendorAccountId
,CAST(0 as bit) as IsVendorAccount
,null as VendorAccountReference
,null as VendorCompanyId
,a.[AccountId]
,a.[CompanyId]
,a.[CompanyAccountTypeId]
,ag.[CompanyAccountGroupId]
,ag.[Name] as CompanyAccountGroupName
,a.[RegionId]
,a.[Name]
,CONCAT(c.ShortName + ': ', a.[Name], ' [' + a.[Code] +']') AS DisplayName
,a.[Code]
,a.[Address]
,a.[Email]
,a.[IncludeEscalationEmail]
,a.[GPSLat]
,a.[GPSLong]
,a.[Telephone]
,a.[VATNumber]
,a.[AutoReceive]
,a.[AutoIssue]
,a.[IsBillableToAccount]
,a.[BillingStart]
,a.[IsEquipmentDepot]
,a.[IsShiftAttendanceEnabled]
,a.[ShiftMinHoursForLunchDeduction]
,a.[NightShiftStart]
,a.[NightShiftEnd]
,a.[ShiftStartDayOfMonth]
,a.[OperatingHoursStart]
,a.[OperatingHoursEnd]
,a.[LoadBays]
,a.[LoadInterval]
,a.[ArrivalInterval]
,a.[OverrideStockTakeCloseBalanceTime]
--,a.[RFEquipment]
,a.[temp_IgnoreVendorIssueViaSAP]
,a.[Archived]
,a.[CreatedDate]
,a.[CreatedBy_PersonId]
,a.[UpdatedDate]
,a.[UpdatedBy_PersonId]
,cat.Name as CompanyAccountTypeName
,at.Name as AccountTypeName
,at.AccountTypeId
,at.EnumAccountType
,r.Name as Region
,c.Name as Company
,CONCAT(c.Code, ': ', a.Name, ' ',a.Code, ' ', c.Name, ' ', r.Name, ' ', at.Name, ' ', r.Code, ' ') as ViewSearchColumn
FROM
[Account] a
JOIN Company c on (a.CompanyId = c.CompanyId)
JOIN CompanyAccountType cat on (a.CompanyAccountTypeId = cat.CompanyAccountTypeId)
JOIN AccountType at on (cat.AccountTypeId = at.AccountTypeId)
LEFT OUTER JOIN vCompanyAccountGroup ag on (a.CompanyAccountGroupId = ag.CompanyAccountGroupId)
LEFT OUTER JOIN Region r on (a.RegionId = r.RegionId)
UNION
SELECT
cv.[CompanyVendorAccountId]
,CAST(1 as bit) as IsVendorAccount
,cv.[VendorAccountReference]
,a.[CompanyId] as VendorCompanyId
,a.[AccountId]
,cv.[CompanyId]
,cv.[CompanyAccountTypeId]
,ag.[CompanyAccountGroupId]
,ag.[Name] as CompanyAccountGroupName
,a.[RegionId]
,a.[Name]
,CONCAT(c.ShortName + ': ', a.[Name], ' [' + cv.[VendorAccountReference] +']') AS DisplayName
,cv.[VendorAccountReference] as [Code]
,a.[Address]
,a.[Email]
,a.[IncludeEscalationEmail]
,a.[GPSLat]
,a.[GPSLong]
,a.[Telephone]
,a.[VATNumber]
,a.[AutoReceive]
,a.[AutoIssue]
,a.[IsBillableToAccount]
,a.[BillingStart]
,a.[IsEquipmentDepot]
,a.[IsShiftAttendanceEnabled]
,a.[ShiftMinHoursForLunchDeduction]
,a.[NightShiftStart]
,a.[NightShiftEnd]
,a.[ShiftStartDayOfMonth]
,a.[OperatingHoursStart]
,a.[OperatingHoursEnd]
,a.[LoadBays]
,a.[LoadInterval]
,a.[ArrivalInterval]
,a.[OverrideStockTakeCloseBalanceTime]
--,a.[RFEquipment]
,a.[temp_IgnoreVendorIssueViaSAP]
,cv.[Archived]
,cv.[CreatedDate]
,cv.[CreatedBy_PersonId]
,cv.[UpdatedDate]
,cv.[UpdatedBy_PersonId]
,cat.Name as CompanyAccountTypeName
,at.Name as AccountTypeName
,at.AccountTypeId
,at.EnumAccountType
,r.Name as Region
,c.Name as Company
,CONCAT(c.Code, ': ', a.Name, ' ',a.Code, ' ', c.Name, ' ', r.Name, ' ', at.Name, ' ', r.Code, ' ') as ViewSearchColumn
FROM
[CompanyVendorAccount] cv
JOIN Company c on (cv.CompanyId = c.CompanyId)
JOIN CompanyAccountType cat on (cv.CompanyAccountTypeId = cat.CompanyAccountTypeId)
JOIN AccountType at on (cat.AccountTypeId = at.AccountTypeId)
JOIN Account a on (cv.VendorAccountId = a.AccountId)
LEFT OUTER JOIN Region r on (a.RegionId = r.RegionId)
LEFT OUTER JOIN vCompanyAccountGroup ag on (cv.CompanyAccountGroupId = ag.CompanyAccountGroupId)
WHERE
cv.CompanyId != a.CompanyId
The only think I added, was this cte:
,cte_ranking_order as
(
SELECT ROW_NUMBER() over (PARTITION BY AccountId, CompanyID ORDER BY AccountId, CompanyId) as rankNumber,* FROM cte_accounts_data
)
The point of this was to only select unique Accounts from the original select lsits, by giving it a ROW_NUMBER() and partitioning the data with over (PARTITION BY AccountId, CompanyID ORDER BY AccountId, CompanyId).
When a stored procedure tries to join this View with some other views, passed in a specific #AccountId, the stored procedure executes for about 5min.
I really am not sure what could posiible cause this?

I was going to add this as a comment, but I couldn't really give you a good example of what I was trying to say...
Have you eliminated SQL's parameter sniffing as the culprit? I've had it happen many times, running the query in a query window is fast, but the sp takes forever. This can happen when parameter sniffing kicks in. You can avoid this by assigning the passed variables to new variables within the SP and then referencing those instead.
So, for example:
CREATE PROCEDURE dbo.MyProcedureName(
#AccountID INT
)
BEGIN
-- Prevent parameter sniffing.
DECLARE #MyAccountID INT = #AccountID;
SELECT
...
FROM dbo.MyView
WHERE
MyView.AccountID = #MyAccountID;
...
END
Just a thought, but this has happened to me before and I beat my head against a wall trying to figure it out.
I know there are other ways (perhaps better) to handle this particular problem, but this solution has always worked for me.
Some additional reading on the subject if interested:
https://www.red-gate.com/simple-talk/sql/t-sql-programming/parameter-sniffing/

Related

SQL Pivot Query for Attendance Report

I have below query written for my attendance report. everything works fine except one thing. i have multiple checkin/checkout allowed in a day in my application now when i run my query it returns checkin, checkout, total, checkin checkout total. the result i expect is something like: checkin, checkout, checkin, checkout.... total.
Below is the query:
SELECT EmployeeID, Employee, [2016-09-01],[2016-09-02],[2016-09-05],[2016-09-06],[2016-09-07],[2016-09-08],[2016-09-09] from
(
SELECT src.EmployeeID, isnull(b.EmployeeName,'') +' '+ isnull(b.LastName,'') Employee
,[CheckinDate]
, ISNULL(CAST(c.LeaveDesc as VARCHAR(max)), STUFF((
SELECT ', ' + CAST(ISNULL(CheckinTime,'') AS VARCHAR(5)) + char(10) + CAST(ISNULL(CheckoutTime,'') AS VARCHAR(5)) +
char(10) + CAST(ISNULL(TotalHours,'') AS VARCHAR(5))
FROM EmployeeDetail
WHERE (EmployeeID = src.EmployeeID and CheckinDate = src.CheckinDate)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'')) AS Result
FROM [EmployeeDetail] as src inner join EmployeeMaster b on src.EmployeeID = b.EmployeeID and src.KindergardenID = b.KindergardenID
left outer join leavetype c on src.leaveid = c.leaveid
WHERE src.KindergardenID = 1
GROUP BY src.EmployeeID, isnull(b.EmployeeName,'') +' '+ isnull(b.LastName,''), CheckinDate,LeaveDesc
) x
pivot
(
max(Result)
for CheckinDate in ([2016-09-01],[2016-09-02],[2016-09-05],[2016-09-06],[2016-09-07],[2016-09-08],[2016-09-09])
) p
Any help in changing the query to make it work as expected is appreciated.
Let me know if i was confusing in asking.
SELECT EmployeeID, Employee, ' + #cols + ' from
(
SELECT src.EmployeeID, isnull(b.EmployeeName,'''') +'' ''+ isnull(b.LastName,'''') Employee
,[CheckinDate]
, ISNULL(CAST(c.LeaveDesc as VARCHAR(max)), isnull(left(convert(time,DATEADD(minute,(SUM(DATEDIFF(MINUTE, ''0:00:00'', TotalHours))),0)),5),''N/A'') + char(10) + STUFF((
SELECT '', '' + CAST(ISNULL(CheckinTime,'''') AS VARCHAR(5)) + ''-'' + CAST(ISNULL(CheckoutTime,'''') AS VARCHAR(5)) +
char(10)
FROM EmployeeDetail
WHERE (EmployeeID = src.EmployeeID and CheckinDate = src.CheckinDate)
FOR XML PATH(''''),TYPE).value(''(./text())[1]'',''VARCHAR(MAX)'')
,1,2,'''')) AS Result
FROM [EmployeeDetail] as src inner join EmployeeMaster b on src.EmployeeID = b.EmployeeID and src.KindergardenID = b.KindergardenID
left outer join leavetype c on src.leaveid = c.leaveid
WHERE src.KindergardenID = ' + CAST(#kindergardenid as varchar(max)) + '
GROUP BY src.EmployeeID, isnull(b.EmployeeName,'''') +'' ''+ isnull(b.LastName,''''), CheckinDate,LeaveDesc
) x
pivot
(
max(Result)
for CheckinDate in (' + #cols + ')
) p

How to merge two queries into one

How can I join these 2 SQL statements? I want the columns of the first and the columns of the second to appear together as one SQL query.
SELECT
E.tbl1_ORG AS Organización, E.tbl1_CODE AS [Orden de Trabajo],
E.tbl1_OBJECT AS Equipo, O.tbl3_POSITION AS Posicion,
E.tbl1_JOBTYPE AS [Tipo de Trabajo],
E.tbl1_DESC AS [Descripcion OT], E.tbl1_WORKADDRESS AS Comentarios,
E.tbl1_REQM AS Error, B.tbl2_PERSON AS Trabajador,
B.tbl2_ENTERED AS Fecha, B.tbl2_HOURS AS Horas
FROM
dbo.table1 AS E
INNER JOIN
dbo.table2 AS B ON E.tbl1_CODE = B.tbl2_EVENT
INNER JOIN
dbo.table3 AS O ON O.tbl3_CODE = E.tbl1_OBJECT
WHERE
E.tbl1_JOBTYPE IN ('PM', 'CM', 'PMM') and
E.tbl1_ORG = #PROMPT('Organización')# and
B.tbl2_ENTERED between #PROMPT('Fecha_Inicio')# and #PROMPT('Fecha_Final')# and
(E.tbl1_REQM = #PROMPT('Error')# OR #PROMPT('Error')# = '%') and
(E.tbl1_OBJECT = #PROMPT('Equipo')# OR #PROMPT('Equipo')# = '%') and
(O.tbl3_POSITION = #PROMPT('Posicion')# OR #PROMPT('Posicion')# = '%')
And:
SELECT
tbl2_event 'Orden de Trabajo',
STUFF((SELECT ', ' + CAST(tbl2_person AS VARCHAR(100)) [text()]
FROM table2
WHERE tbl2_event = t.tbl2_event
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,' ') Empleados,
STUFF((SELECT ', ' + CAST(tbl2_hours AS VARCHAR(100)) [text()]
FROM table2
WHERE tbl2_event = t.tbl2_event
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'), 1, 1, ' ') Horas
FROM table2 t
GROUP BY tbl2_event
Both work perfectly on their own, but I don't know how to merge them.
Add ROW_NUMBER to each query and then FULL JOIN them together. You'll need to decide on the ordering of rows in each query.
WITH
CTE1
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY ...) AS rn,
E.tbl1_ORG AS Organización, E.tbl1_CODE AS [Orden de Trabajo],
E.tbl1_OBJECT AS Equipo, O.tbl3_POSITION AS Posicion,
E.tbl1_JOBTYPE AS [Tipo de Trabajo],
E.tbl1_DESC AS [Descripcion OT], E.tbl1_WORKADDRESS AS Comentarios,
E.tbl1_REQM AS Error, B.tbl2_PERSON AS Trabajador,
B.tbl2_ENTERED AS Fecha, B.tbl2_HOURS AS Horas
FROM
dbo.table1 AS E
INNER JOIN
dbo.table2 AS B ON E.tbl1_CODE = B.tbl2_EVENT
INNER JOIN
dbo.table3 AS O ON O.tbl3_CODE = E.tbl1_OBJECT
WHERE
E.tbl1_JOBTYPE IN ('PM', 'CM', 'PMM') and
E.tbl1_ORG = #PROMPT('Organización')# and
B.tbl2_ENTERED between #PROMPT('Fecha_Inicio')# and #PROMPT('Fecha_Final')# and
(E.tbl1_REQM = #PROMPT('Error')# OR #PROMPT('Error')# = '%') and
(E.tbl1_OBJECT = #PROMPT('Equipo')# OR #PROMPT('Equipo')# = '%') and
(O.tbl3_POSITION = #PROMPT('Posicion')# OR #PROMPT('Posicion')# = '%')
)
,CTE2
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY ...) AS rn,
tbl2_event 'Orden de Trabajo',
STUFF((SELECT ', ' + CAST(tbl2_person AS VARCHAR(100)) [text()]
FROM table2
WHERE tbl2_event = t.tbl2_event
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,' ') Empleados,
STUFF((SELECT ', ' + CAST(tbl2_hours AS VARCHAR(100)) [text()]
FROM table2
WHERE tbl2_event = t.tbl2_event
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'), 1, 1, ' ') Horas
FROM table2 t
GROUP BY tbl2_event
)
SELECT ...
FROM
CTE1 FULL JOIN CTE2 ON CTE1.rn = CTE2.rn
ORDER BY ...
;
If you have more than 2-3 tables to join like this FULL JOIN would quickly become ugly and slow. Have a look at my answer for a similar question for alternative solution: best way to "glue" columns together

Reducing execution time in a run-time constructed query when using views

I have a query that I am using where I only know what variables will be retrieved at run time. I'm using a view to pull all of the variables into a single data set then querying against that data set. It looks something like this:
All variables in the SQL db:
Table A.1, Table A.2, Table A.3
Table B.1, Table B.2, Table B.3
Table C.1, Table C.2, Table C.3
At run time I know that I want the variables Table A.1 and Table A.2 where Table A.1 = SomeNumber. I therefore create a view as:
View 1 = Table A.1, Table B.1
I then query against that view where Table A.1 = SomeNumber
This approach seems to work but it take a long time (30 seconds) to return results because I have 20+ tables and 100+ variables. There are 2K+ records to query against.
Any ideas on how I can improve the response time of this query?
******* HERE IS THE ACTUAL QUERY **********
USE [ays_restructuring_league_live];
GO
ALTER PROCEDURE [dbo].[sp_getVolunteerSummaryDetails]
(#LeagueId int, #p_SearchCriteria varchar(MAX), #p_DataflowId int=null)
WITH
EXECUTE AS CALLER
AS
Begin
SET NOCOUNT ON;
DECLARE #Statement AS varchar(MAX);
Declare #p_DataFieldName as varchar(max);
declare #p_Label as varchar(max);
if (CHARINDEX('DisplayId = ''1'' ',#p_SearchCriteria)>0)/* for multiple record*/
begin
Select b.* into #finalTable from(
SELECT distinct VSI.VolunteerSeasonalId,
VI.VolunteerId,
right(MUS.DetailIdURL_Structure + cast(convert(varchar(max),VI.VolunteerId) as varchar(max)),MUS.DetailIdURL_Length) as NewVolunteerId,
right(MUS.OtherURL_Structure + cast(convert(varchar(max),VSI.SeasonId) as varchar(max)),MUS.OtherURL_Length) as NewSeasonId,
UI.FirstName as VolunteerFirstName,
UI.LastName as VolunteerLastName,
UI.LastName+ ', '+ UI.FirstName as VolunteerName,
UI.Email as VolunteerEmail,
VI.ShirtSizeId,
MUSZ.Size as ShirtSize,
UI.HomePhone as VolunteerHomePhone,
UI.MobilePhone as VolunteerMobilePhone,
UI.WorkPhone as VolunteerWorkPhone,
--convert(varchar,UI.BirthDate,101) as VolunteerBirthDate,
--UI.Address,
--UI.StateId,
--MST.Abbreviation as State,
--UI.CityId,
--MC.Abbreviation as City,
--UI.Zip,
--VI.DrivingLicenceNumber,
--UI.Gender as VolunteerGender,
--VSI.CreatedBy,
--VSI.CreatedOn,
--VSI.UpdatedBy,
--VSI.UpdatedOn,
VSI.StatusId,
VSI.SeasonId,
(SELECT substring ( (SELECT ', ' + cast (b.[Day] as varchar)
FROM (select MD.[Day]
from dbo.Master_Day MD where MD.DayID in (select items from dbo.udf_Split(PP.DaysCanNotPractice, ',')))
b for xml path ('')),2,10000)) as DaysCanNotPractice,
(SELECT substring ( (SELECT ', ' + cast (b.[Time] as varchar)
FROM (select PT.[Time]
from dbo.PreferedTime PT where PT.PreferedTimeId in (select items from dbo.udf_Split(PP.TimeCanNotPractice, ',')))
b for xml path ('')),2,10000)) as TimeCanNotPractice,
--PP.LocationId,
--PP.LocationRankId,
(select substring((select ', ' + cast (b.ShortName as varchar)
from (select ML.ShortName
from dbo.Master_Location ML
where ML.LocationID in (select items from dbo.udf_Split(PP.LocationId, ',')))
as b for xml path('')),2,1000000)) as ShortName,
(SELECT MR.[Rank]
FROM dbo.Master_Rank MR
WHERE MR.RankID = PP.LocationRankId) as LocationRank,
--PP.DayOfWeekId,
--PP.DayOfWeekRankId,
(select substring((select ', ' + cast (b.[Day] as varchar)
from (select MD.[Day] from dbo.Master_Day MD
where MD.DayID in (select items from dbo.udf_Split(PP.DayOfWeekId,',')))
as b for xml path('')),2,1000000)) as [DayOfWeek],
(select MR.[Rank]
from dbo.Master_Rank MR
where MR.RankID = PP.DayOfWeekRankId)AS DayOfWeekRank,
--PP.TimeOfDayId,
--PP.TimeOfDayRankId,
(select substring((select ', ' + cast (b.[Time] as varchar)
from (select [Time]
from dbo.PreferedTime PT
where PT.PreferedTimeId in (select items from dbo.udf_Split(PP.TimeOfDayId,',')))
as b for xml path('')),2,1000000)) as TimeOfDay,
(SELECT MR.[Rank]
FROM dbo.Master_Rank MR
WHERE MR.RankID = PP.TimeOfDayRankId) as TimeOfDayRank,
--case when MVP.VolunteerPosition is null then '' else ( case when MD.Abbreviation is null then MVP.VolunteerPosition else '('+MD.Abbreviation+') '+MVP.VolunteerPosition end)end as VolunteeredPosition,
--case when MVP.VolunteerPosition is null then '' else ( case when VRP.PositionId>5 then MVP.VolunteerPosition else '('+MD.Abbreviation+') '+MVP.VolunteerPosition end)end as VolunteeredPosition,
case when MVP.VolunteerPosition is null then '' else
case when VRP.PositionId>5 then MVP.VolunteerPosition else
case when MD.Abbreviation is null then MVP.VolunteerPosition else
'('+MD.Abbreviation+') '+MVP.VolunteerPosition end
end
end as VolunteeredPosition,
case when VRP.PositionId is null then '' else convert(varchar(50),VRP.PositionId) end as VolunteeredPositionId,
case when VRP.DivisionId is null then '' else convert(varchar(50),VRP.DivisionId) end as VolunteeredDivisionId,
'' as AssignedPosition,
'' as AssignedVolunteerPositionId,
'' as AssignedDivisionId,
(SELECT substring ( (SELECT '; ' + cast (b.PlayerName AS varchar(max))
FROM (SELECT DISTINCT ('('+MD.Abbreviation+') '+ PPI.PlayerLastName + ', '+PPI.PlayerFirstName+'$'+'001'+right(MUS.DetailIdURL_Structure + cast(convert(varchar(max),PPI.PlayerId) as varchar(max)),MUS.DetailIdURL_Length)) AS PlayerName
FROM dbo.Player_PermanentInfo PPI,dbo.Player_SeasonalInfo PSI,dbo.Master_Division MD
WHERE (PPI.ParentId1=UI.UserId or PPI.ParentId2=UI.UserId)
and PSI.PlayerId=PPI.PlayerId
and PSI.IsAvailable=1 and PSI.SeasonId=VSI.SeasonID
and PSI.DivisionId=MD.DivisionId
)b FOR XML PATH ( '' )),2,100000))AS PlayerName,
/*
(SELECT substring ( (SELECT ';' + cast (b.PlayerLastName AS varchar(max))
FROM (SELECT DISTINCT PPI.PlayerLastName
FROM dbo.Player_PermanentInfo PPI,dbo.Player_SeasonalInfo PSI,dbo.Master_Division MD
WHERE (PPI.ParentId1=UI.UserId or PPI.ParentId2=UI.UserId)
and PSI.PlayerId=PPI.PlayerId
and PSI.IsAvailable=1 and PSI.SeasonId=VSI.SeasonID
and PSI.DivisionId=MD.DivisionId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS PlayerLastName,
(SELECT substring ( (SELECT ';' + cast (b.PlayerFirstName AS varchar(max))
FROM (SELECT DISTINCT PPI.PlayerFirstName
FROM dbo.Player_PermanentInfo PPI,dbo.Player_SeasonalInfo PSI,dbo.Master_Division MD
WHERE (PPI.ParentId1=UI.UserId or PPI.ParentId2=UI.UserId)
and PSI.PlayerId=PPI.PlayerId
and PSI.IsAvailable=1 and PSI.SeasonId=VSI.SeasonID
and PSI.DivisionId=MD.DivisionId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS PlayerFirstName,*/
/*(SELECT substring ((SELECT ','
+ cast (b.ColorID AS varchar)
FROM (SELECT DISTINCT (VBGD.ColorID)
FROM dbo.VolunteerBackGroundDetail VBGD,dbo.Master_Color MCL
WHERE MCL.ColorID= VBGD.ColorID
and VBGD.VolunteerId = VSI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS Result,*/
(SELECT substring((SELECT ','
+ cast (b.CheckTypeID AS varchar)
FROM (SELECT DISTINCT (VBI.CheckTypeID)
FROM dbo.Volunteer_BackgroundInfo VBI
WHERE VBI.VolunteerId = VSI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS BGCheckType,
(SELECT substring ((SELECT ','
+ cast (b.ColorName AS varchar)
FROM (SELECT DISTINCT (MCL.ColorName)
FROM dbo.Volunteer_BackgroundInfo VBI,dbo.Master_Color MCL
WHERE MCL.ColorID= VBI.ColorID
and VBI.VolunteerId = VI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS BGCheckResult,
/*(SELECT substring((SELECT ','
+ cast (b.CheckType AS varchar)
FROM (SELECT DISTINCT (MVCT.CheckType)
FROM dbo.Volunteer_BackgroundInfo VBI,dbo.Master_VolunteerCheckType MVCT
WHERE VBI.VolunteerId = VSI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
and VBI.CheckTypeID=MVCT.CheckTypeId)
b
FOR XML PATH ( '' )),
2,
100000
))
AS CheckType,*/
(SELECT substring((SELECT ','
+ cast (b.DatePerformed AS varchar)
FROM (SELECT DISTINCT Convert(varchar,VBI.DatePerformed,101) as DatePerformed
FROM dbo.Volunteer_BackgroundInfo VBI
WHERE VBI.VolunteerId = VI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
)
b FOR XML PATH ( '' )),2,100000))AS BGCheckDate,
/*(SELECT substring((SELECT ','+ cast(b.EventId as varchar(max))
from(select distinct VCD.EventId
from CheckIn_VolunteerCheckInDetails VCD,CheckIn_CoachCheckInDetails CCD
where VCD.EventId=CCD.EventId
and (VCD.VolunteerSeasonalId=VSI.VolunteerSeasonalId or CCD.VolunteerSeasonalId=VSI.VolunteerSeasonalId))
b for xml path('')),2,100000)) as CheckInEventID,*/
--'' as CheckInEventID,
/*(SELECT substring((SELECT ', '+ cast(b.EventName as varchar(max))
from(select distinct CEM.EventName
from CheckIn_EventMaster CEM, CheckIn_VolunteerCheckInDetails VCD,CheckIn_CoachCheckInDetails CCD
where CEM.CheckInEventId=VCD.EventId AND CEM.CheckInEventId=CCD.EventId
and (VCD.VolunteerSeasonalId=VSI.VolunteerSeasonalId or CCD.VolunteerSeasonalId=VSI.VolunteerSeasonalId))
b for xml path('')),2,100000)) as CheckInEventName,*/
/*(SELECT substring((SELECT ','+ cast(b.EventId as varchar(max))
from(select distinct VCD.EventId
from CheckIn_VolunteerCheckInDetails VCD
where VCD.VolunteerSeasonalId=VSI.VolunteerSeasonalId)
b for xml path('')),2,100000)) as CheckInEventID,
(SELECT substring((SELECT ', '+ cast(b.EventName as varchar(max))
from(select distinct CEM.EventName
from CheckIn_EventMaster CEM, CheckIn_VolunteerCheckInDetails VCD
where CEM.CheckInEventId=VCD.EventId
and VCD.VolunteerSeasonalId=VSI.VolunteerSeasonalId)
b for xml path('')),2,100000)) as CheckInEventName,*/
/*(SELECT substring((SELECT ','
+ cast (b.DatePerformed AS varchar)
FROM (SELECT DISTINCT Convert(varchar,VBI.DatePerformed,101) as DatePerformed
FROM dbo.Volunteer_BackgroundInfo VBI
WHERE VBI.VolunteerId = VSI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS DatePerformed,*/
/*case when exists(select *
from dbo.VolunteerApproval
where VolunteerApproval.VolunteerSeasonalID = VSI.VolunteerSeasonalId
and VolunteerApproval.LeagueId = VSI.LeagueId
and VolunteerApproval.ApprovedStatus = 1) then 'i_tick.gif' else 'remove_Icon.png' end as IsApproved, */
VSI.VolunteerSeasonalStatusId as Approved,
case when VSI.VolunteerSeasonalStatusId = 1 then 'i_tick.gif' else 'remove_Icon.png' end as IsApproved ,
--,MS.SeasonName
'1' as DisplayId,
case when VSI.SeasonId = 8 then '2014/15 Regular Season' else
case when VSI.SeasonId = 7 then '2013/14 Regular Season' else '2014/15 FYBA Fall Academy'
end
end as SeasonName,
VSI.SchedulingPriority
--into #finalTable
FROM dbo.Master_Url_Setting MUS, dbo.Volunteer_Info VI
inner join dbo.Volunteer_SeasonalInfo VSI on VSI.VolunteerId = VI.VolunteerId
inner join User_Info UI on UI.UserId=VI.UserId
inner JOIN dbo.Volunteer_Requested_Position VRP
ON VRP.VolunteerSeasonalId = VSI.VolunteerSeasonalId
LEFT OUTER JOIN dbo.Master_UniformSize MUSZ
ON MUSZ.UniformSizeId = VI.ShirtSizeId
left OUTER JOIN dbo.PracticePreference PP
ON PP.VolunteerSeasonalId = VSI.VolunteerSeasonalId
--left OUTER JOIN dbo.Volunteer_Requested_Position VRP
--ON VRP.VolunteerSeasonalId = VSI.VolunteerSeasonalId
left outer join dbo.Master_Division MD
ON VRP.DivisionId = MD.DivisionId
left outer join dbo.Master_VolunteerPosition MVP
ON MVP.VolunteerPositionId = VRP.PositionId
WHERE VSI.IsAvailable = 1
AND VSI.LeagueId = #LeagueId
and VSI.Seasonid in (7,8,9)
--and VSI.VolunteerId=878
union
SELECT distinct VSI.VolunteerSeasonalId,
VI.VolunteerId,
right(MUS.DetailIdURL_Structure + cast(convert(varchar(max),VI.VolunteerId) as varchar(max)),MUS.DetailIdURL_Length) as NewVolunteerId,
right(MUS.OtherURL_Structure + cast(convert(varchar(max),VSI.SeasonId) as varchar(max)),MUS.OtherURL_Length) as NewSeasonId,
UI.FirstName as VolunteerFirstName,
UI.LastName as VolunteerLastName,
UI.LastName+ ', '+ UI.FirstName as VolunteerName,
UI.Email as VolunteerEmail,
VI.ShirtSizeId,
MUSZ.Size as ShirtSize,
UI.HomePhone as VolunteerHomePhone,
UI.MobilePhone as VolunteerMobilePhone,
UI.WorkPhone as VolunteerWorkPhone,
--convert(varchar,UI.BirthDate,101) as VolunteerBirthDate,
--UI.Address,
--UI.StateId,
--MST.Abbreviation as State,
--UI.CityId,
--MC.Abbreviation as City,
--UI.Zip,
--VI.DrivingLicenceNumber,
--UI.Gender as VolunteerGender,
--VSI.CreatedBy,
--VSI.CreatedOn,
--VSI.UpdatedBy,
--VSI.UpdatedOn,
VSI.StatusId,
VSI.SeasonId,
(SELECT substring ( (SELECT ', ' + cast (b.[Day] as varchar)
FROM (select MD.[Day]
from dbo.Master_Day MD where MD.DayID in (select items from dbo.udf_Split(PP.DaysCanNotPractice, ',')))
b for xml path ('')),2,10000)) as DaysCanNotPractice,
(SELECT substring ( (SELECT ', ' + cast (b.[Time] as varchar)
FROM (select PT.[Time]
from dbo.PreferedTime PT where PT.PreferedTimeId in (select items from dbo.udf_Split(PP.TimeCanNotPractice, ',')))
b for xml path ('')),2,10000)) as TimeCanNotPractice,
--PP.LocationId,
--PP.LocationRankId,
(select substring((select ', ' + cast (b.ShortName as varchar)
from (select ML.ShortName
from dbo.Master_Location ML
where ML.LocationID in (select items from dbo.udf_Split(PP.LocationId, ',')))
as b for xml path('')),2,1000000)) as ShortName,
(SELECT MR.[Rank]
FROM dbo.Master_Rank MR
WHERE MR.RankID = PP.LocationRankId) as LocationRank,
--PP.DayOfWeekId,
--PP.DayOfWeekRankId,
(select substring((select ', ' + cast (b.[Day] as varchar)
from (select MD.[Day] from dbo.Master_Day MD
where MD.DayID in (select items from dbo.udf_Split(PP.DayOfWeekId,',')))
as b for xml path('')),2,1000000)) as [DayOfWeek],
(select MR.[Rank]
from dbo.Master_Rank MR
where MR.RankID = PP.DayOfWeekRankId)AS DayOfWeekRank,
--PP.TimeOfDayId,
--PP.TimeOfDayRankId,
(select substring((select ', ' + cast (b.[Time] as varchar)
from (select [Time]
from dbo.PreferedTime PT
where PT.PreferedTimeId in (select items from dbo.udf_Split(PP.TimeOfDayId,',')))
as b for xml path('')),2,1000000)) as TimeOfDay,
(SELECT MR.[Rank]
FROM dbo.Master_Rank MR
WHERE MR.RankID = PP.TimeOfDayRankId) as TimeOfDayRank,
'' as VolunteeredPosition,
'' as VolunteeredPositionId,
'' as VolunteeredDivisionId,
case when AMVP.VolunteerPosition is null then '' else (case when TV.VolunteerPositionId>5 then AMVP.VolunteerPosition else '('+AMD.Abbreviation+') '+AMVP.VolunteerPosition end)end as AssignedPosition,
--case when AMVP.VolunteerPosition is null then '' else(case when AMD.Abbreviation is null then AMVP.VolunteerPosition else '('+AMD.Abbreviation+') '+AMVP.VolunteerPosition end)end as AssignedPosition,
case when TV.VolunteerPositionId is null then '' else convert(varchar(50),TV.VolunteerPositionId) end as AssignedVolunteerPositionId,
case when MT.DivisionId is null then '' else convert(varchar(50),MT.DivisionId) end as AssignedDivisionId,
(SELECT substring ( (SELECT '; ' + cast (b.PlayerName AS varchar(max))
FROM (SELECT DISTINCT ('('+MD.Abbreviation+') '+ PPI.PlayerLastName + ', '+PPI.PlayerFirstName+'$'+'001'+right(MUS.DetailIdURL_Structure + cast(convert(varchar(max),PPI.PlayerId) as varchar(max)),MUS.DetailIdURL_Length)) AS PlayerName
FROM dbo.Player_PermanentInfo PPI,dbo.Player_SeasonalInfo PSI,dbo.Master_Division MD
WHERE (PPI.ParentId1=UI.UserId or PPI.ParentId2=UI.UserId)
and PSI.PlayerId=PPI.PlayerId
and PSI.IsAvailable=1 and PSI.SeasonId=VSI.SeasonID
and PSI.DivisionId=MD.DivisionId
)b FOR XML PATH ( '' )),2,100000))AS PlayerName,
(SELECT substring((SELECT ','
+ cast (b.CheckTypeID AS varchar)
FROM (SELECT DISTINCT (VBI.CheckTypeID)
FROM dbo.Volunteer_BackgroundInfo VBI
WHERE VBI.VolunteerId = VSI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS BGCheckType,
(SELECT substring ((SELECT ','
+ cast (b.ColorName AS varchar)
FROM (SELECT DISTINCT (MCL.ColorName)
FROM dbo.Volunteer_BackgroundInfo VBI,dbo.Master_Color MCL
WHERE MCL.ColorID= VBI.ColorID
and VBI.VolunteerId = VI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS BGCheckResult,
(SELECT substring((SELECT ','
+ cast (b.DatePerformed AS varchar)
FROM (SELECT DISTINCT Convert(varchar,VBI.DatePerformed,101) as DatePerformed
FROM dbo.Volunteer_BackgroundInfo VBI
WHERE VBI.VolunteerId = VI.VolunteerId --VBGD.VolunteerSeasonalID = VSI.VolunteerSeasonalId
)
b FOR XML PATH ( '' )),2,100000))AS BGCheckDate,
VSI.VolunteerSeasonalStatusId as Approved,
case when VSI.VolunteerSeasonalStatusId = 1 then 'i_tick.gif' else 'remove_Icon.png' end as IsApproved ,
--,MS.SeasonName
'1' as DisplayId,
case when VSI.SeasonId = 8 then '2014/15 Regular Season' else
case when VSI.SeasonId = 7 then '2013/14 Regular Season' else '2014/15 FYBA Fall Academy'
end
end as SeasonName,
VSI.SchedulingPriority
--into #finalTable
FROM dbo.Master_Url_Setting MUS, dbo.Volunteer_Info VI
inner join dbo.Volunteer_SeasonalInfo VSI on VSI.VolunteerId = VI.VolunteerId
inner join User_Info UI on UI.UserId=VI.UserId
inner JOIN dbo.TeamVolunteers TV
ON TV.VolunteerSeasonalId= VSI.VolunteerSeasonalId
LEFT OUTER JOIN dbo.Master_UniformSize MUSZ
ON MUSZ.UniformSizeId = VI.ShirtSizeId
left OUTER JOIN dbo.PracticePreference PP
ON PP.VolunteerSeasonalId = VSI.VolunteerSeasonalId
--left OUTER JOIN dbo.TeamVolunteers TV
--ON TV.VolunteerSeasonalId= VSI.VolunteerSeasonalId
LEFT OUTER JOIN dbo.Master_Teams MT
ON MT.TeamId = TV.TeamId
left outer join dbo.Master_Division AMD
ON MT.DivisionId = AMD.DivisionId
left outer join dbo.Master_VolunteerPosition AMVP
ON AMVP.VolunteerPositionId = TV.VolunteerPositionId
WHERE VSI.IsAvailable = 1
AND VSI.LeagueId = #LeagueId
and VSI.Seasonid in (7,8,9)
--and VSI.VolunteerId=878
)b
--where VolunteerSeasonalId=7225
OPTION (FORCE ORDER);
IF #p_DataflowId IS NULL
BEGIN
SET #Statement = 'Select * from #finalTable ' + #p_SearchCriteria+' OPTION (FORCE ORDER)';
EXEC (#Statement);
END
ELSE
BEGIN
CREATE TABLE [#tempExportFields]([DataFieldName] varchar(max),Label varchar(max));
Set #Statement = 'Select '
insert into #tempExportFields exec sp_getControlsorderingForExport #p_DataflowId;
set #Statement = 'Select '+(select substring((select ', '+ b.Label from (Select DataFieldName +' as ' + '['+ Label +']' as Label from #tempExportFields) as b for xml path('')),2,100000)) + ' from #finalTable ' + #p_SearchCriteria;
--select (#Statement);
EXEC (#Statement);
DROP TABLE #tempExportFields;
END
DROP TABLE #finalTable;
SET NOCOUNT OFF;
end
else /* for single Record record*/
begin
SELECT distinct VSI.VolunteerSeasonalId,
VI.VolunteerId,
right(MUS.DetailIdURL_Structure + cast(convert(varchar(max),VI.VolunteerId) as varchar(max)),MUS.DetailIdURL_Length) as NewVolunteerId,
right(MUS.OtherURL_Structure + cast(convert(varchar(max),VSI.SeasonId) as varchar(max)),MUS.OtherURL_Length) as NewSeasonId,
UI.FirstName as VolunteerFirstName,
UI.LastName as VolunteerLastName,
UI.LastName+ ', '+ UI.FirstName as VolunteerName,
UI.Email as VolunteerEmail,
VI.ShirtSizeId,
MUSZ.Size as ShirtSize,
UI.HomePhone as VolunteerHomePhone,
UI.MobilePhone as VolunteerMobilePhone,
UI.WorkPhone as VolunteerWorkPhone,
--convert(varchar,UI.BirthDate,101) as VolunteerBirthDate,
--UI.Address,
--UI.StateId,
--MST.Abbreviation as State,
--UI.CityId,
--MC.Abbreviation as City,
--UI.Zip,
--VI.DrivingLicenceNumber,
--UI.Gender as VolunteerGender,
--VSI.CreatedBy,
--VSI.CreatedOn,
--VSI.UpdatedBy,
--VSI.UpdatedOn,
VSI.StatusId,
VSI.SeasonId,
(SELECT substring ( (SELECT ', ' + cast (b.[Day] as varchar)
FROM (select MD.[Day]
from dbo.Master_Day MD where MD.DayID in (select items from dbo.udf_Split(PP.DaysCanNotPractice, ',')))
b for xml path ('')),2,10000)) as DaysCanNotPractice,
(SELECT substring ( (SELECT ', ' + cast (b.[Time] as varchar)
FROM (select PT.[Time]
from dbo.PreferedTime PT where PT.PreferedTimeId in (select items from dbo.udf_Split(PP.TimeCanNotPractice, ',')))
b for xml path ('')),2,10000)) as TimeCanNotPractice,
--PP.LocationId,
--PP.LocationRankId,
(select substring((select ', ' + cast (b.ShortName as varchar)
from (select ML.ShortName
from dbo.Master_Location ML
where ML.LocationID in (select items from dbo.udf_Split(PP.LocationId, ',')))
as b for xml path('')),2,1000000)) as ShortName,
(SELECT MR.[Rank]
FROM dbo.Master_Rank MR
WHERE MR.RankID = PP.LocationRankId) as LocationRank,
--PP.DayOfWeekId,
--PP.DayOfWeekRankId,
(select substring((select ', ' + cast (b.[Day] as varchar)
from (select MD.[Day] from dbo.Master_Day MD
where MD.DayID in (select items from dbo.udf_Split(PP.DayOfWeekId,',')))
as b for xml path('')),2,1000000)) as [DayOfWeek],
(select MR.[Rank]
from dbo.Master_Rank MR
where MR.RankID = PP.DayOfWeekRankId)AS DayOfWeekRank,
--PP.TimeOfDayId,
--PP.TimeOfDayRankId,
(select substring((select ', ' + cast (b.[Time] as varchar)
from (select [Time]
from dbo.PreferedTime PT
where PT.PreferedTimeId in (select items from dbo.udf_Split(PP.TimeOfDayId,',')))
as b for xml path('')),2,1000000)) as TimeOfDay,
(SELECT MR.[Rank]
FROM dbo.Master_Rank MR
WHERE MR.RankID = PP.TimeOfDayRankId) as TimeOfDayRank,
(SELECT substring ( (SELECT ',' + cast (b.PositionId AS varchar)
FROM (SELECT DISTINCT (VRP1.PositionId)
FROM dbo.Volunteer_Requested_Position VRP1
WHERE VRP1.VolunteerSeasonalId = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS VolunteeredPositionId,
(SELECT substring ( (SELECT ';' + cast (b.VolunteerPosition AS varchar)
FROM (SELECT DISTINCT (case when VRP1.PositionId>5 then MVP.VolunteerPosition else '('+MD.Abbreviation+') '+MVP.VolunteerPosition end)as VolunteerPosition
FROM dbo.Master_VolunteerPosition MVP,dbo.Volunteer_Requested_Position VRP1
left outer join dbo.Master_Division MD ON VRP1.DivisionId = MD.DivisionId
WHERE MVP.VolunteerPositionId = VRP1.PositionId
AND VRP1.VolunteerSeasonalId = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS VolunteeredPosition,
/*(SELECT substring ( (SELECT ';' + cast (b.VolunteerPosition AS varchar)
FROM (SELECT DISTINCT (case when MD.Abbreviation is null then MVP.VolunteerPosition else '('+MD.Abbreviation+') '+MVP.VolunteerPosition end)as VolunteerPosition
FROM dbo.Master_VolunteerPosition MVP,dbo.Volunteer_Requested_Position VRP1
left outer join dbo.Master_Division MD ON VRP1.DivisionId = MD.DivisionId
WHERE MVP.VolunteerPositionId = VRP1.PositionId
AND VRP1.VolunteerSeasonalId = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS VolunteeredPosition,*/
(SELECT substring ( (SELECT ',' + cast (b.DivisionId AS varchar)
FROM (SELECT DISTINCT (VRP1.DivisionId)
FROM dbo.Volunteer_Requested_Position VRP1
WHERE VRP1.VolunteerSeasonalId = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS VolunteeredDivisionId,
/*(SELECT substring ( (SELECT ', ' + cast (b.Abbreviation AS varchar)
FROM (SELECT DISTINCT (MD.Abbreviation)
FROM dbo.Volunteer_Requested_Position VRP1,dbo.Master_Division MD
WHERE VRP1.VolunteerSeasonalId = VSI.VolunteerSeasonalId
and VRP1.DivisionId=MD.DivisionId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS Abbreviation,*/ /*VolunteeredDivision*/
(SELECT substring ( (SELECT ',' + cast (b.VolunteerPositionId AS varchar)
FROM (SELECT DISTINCT (TV.VolunteerPositionId)
FROM dbo.TeamVolunteers TV
WHERE TV.VolunteerSeasonalId = VSI.VolunteerSeasonalId
)
b
FOR XML PATH ( '' )),
2,
100000
))
AS AssignedVolunteerPositionId,
(SELECT substring ( (SELECT ';' + cast (b.VolunteerPosition AS varchar)
......TRUNCATED

Concatenate many rows into a single text string

I'm trying to concatenate several names into a single column but I'm having trouble getting there.
DECLARE #Names VARCHAR(8000)
SELECT
p.Pato_Id
#Names = COALESCE(#Names + ', ', '') + e.First_Name + ' ' + e.Last_Name
FROM
Patos p
LEFT JOIN
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN
Person e
ON
po.Owner_Id = e.Person_Id
How can this be done?
EDIT:
When I'm making a normal select I getting
PatoID First Last
0 John Wort
0 Dan Mass
1 Till Bos
2 Wrap Sim
2 Port Lock
And what I want is:
PatoID Names
0 John Wort, Dan Mass
1 Till Bos
2 Wrap Sim, Port Lock
You have left join which indicate that you can have null names. This would reset the values of names should that occur.
;with cte as
(
SELECT
p.Pato_Id,
coalesce(e.First_Name, '') + coalesce(' ' + e.Last_Name, '') Name
FROM
Patos p
LEFT JOIN
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN
Person e
ON
po.Owner_Id = e.Person_Id
)
select t.Pato_id
,STUFF((
select ',' + [name]
from cte t1
where t1.Pato_Id = t.Pato_Id
for xml path(''), type
).value('.', 'varchar(max)'), 1, 1, '') [Names]
from cte t
group by t.Pato_id
Try this,
DECLARE #Names VARCHAR(8000)
SELECT
p.Pato_Id,
'ServerName' = COALESCE(#Names + ', ', '') + e.First_Name + ' ' + e.Last_Name
FROM
Patos p
LEFT JOIN
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN
Person e
ON
po.Owner_Id = e.Person_Id
I think you want this,
WITH Sales_CTE (Pato_Id, First, Last)
AS
(
Select p.Pato_Id , e.First , e.Last
FROM
Patos p
LEFT JOIN
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN
Person e
ON
po.Owner_Id = e.Person_Id
)
SELECT Pato_Id,
Substring((Select ',' + ISNULL(First,'') + ISNULL(Last,'') From Sales_CTE B Where B.Pato_Id=A.Pato_Id For XML Path('')),2,8000) As names
from Sales_CTE A group by Pato_Id;

How to declare the columns dynamically in a Select query using PIVOT

I am writing a query to get the address for PersonID. Following query is working for me but it only returns with two Addresses. I want to handle the 'n' number of address with a single query. Is there any way to do this?
Many thanks
SELECT
PersonID, PersonName
[Address1], [Address2]
FROM
(
SELECT
P.PersonID,
P.PersonName,
(ROW_NUMBER() OVER(PARTITION BY P.PersonID ORDER BY A.AddressID)) RowID
FROM tblPerson
INNER JOIN tblAddress AS A ON A.PersonID = P.PersonID
) AS AddressTable
PIVOT
(
MAX(AddressID)
FOR RowID IN ([Address1], [Address2])
) AS PivotTable;
Assuming the following tables and sample data:
USE tempdb;
GO
CREATE TABLE dbo.tblPerson(PersonID INT, PersonName VARCHAR(255));
INSERT dbo.tblPerson SELECT 1, 'Bob'
UNION ALL SELECT 2, 'Charlie'
UNION ALL SELECT 3, 'Frank'
UNION ALL SELECT 4, 'Amore';
CREATE TABLE dbo.tblAddress(AddressID INT, PersonID INT, [Address] VARCHAR(255));
INSERT dbo.tblAddress SELECT 1,1,'255 1st Street'
UNION ALL SELECT 2,2,'99 Elm Street'
UNION ALL SELECT 3,2,'67 Poplar Street'
UNION ALL SELECT 4,2,'222 Oak Ave.'
UNION ALL SELECT 5,1,'36 Main Street, Suite 22'
UNION ALL SELECT 6,4,'77 Sicamore Ct.';
The following query gets the results you want, and shows how it handles 0, 1 or n addresses. In this case the highest number is 3 but you can play with more addresses if you like by adjusting the sample data slightly.
DECLARE #col NVARCHAR(MAX) = N'',
#sel NVARCHAR(MAX) = N'',
#from NVARCHAR(MAX) = N'',
#query NVARCHAR(MAX) = N'';
;WITH m(c) AS
(
SELECT TOP 1 c = COUNT(*)
FROM dbo.tblAddress
GROUP BY PersonID
ORDER BY c DESC
)
SELECT #col = #col + ',[Address' + RTRIM(n.n) + ']',
#sel = #sel + ',' + CHAR(13) + CHAR(10) + '[Address' + RTRIM(n.n) + '] = x'
+ RTRIM(n.n) + '.Address',
#from = #from + CHAR(13) + CHAR(10) + ' LEFT OUTER JOIN xMaster AS x'
+ RTRIM(n.n) + ' ON x' + RTRIM(n.n) + '.PersonID = p.PersonID AND x'
+ RTRIM(n.n) + '.rn = ' + RTRIM(n.n)
FROM m CROSS JOIN (SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_columns) AS n WHERE n.n <= m.c;
SET #query = N';WITH xMaster AS
(
SELECT PersonID, Address,
rn = ROW_NUMBER() OVER (PARTITION BY PersonID ORDER BY Address)
FROM dbo.tblAddress
)
SELECT PersonID, PersonName' + #col
+ ' FROM
(
SELECT p.PersonID, p.PersonName, ' + STUFF(#sel, 1, 1, '')
+ CHAR(13) + CHAR(10) + ' FROM dbo.tblPerson AS p ' + #from + '
) AS Addresses;';
PRINT #query;
--EXEC sp_executesql #query;
If you print the SQL you will see this result:
;WITH xMaster AS
(
SELECT PersonID, Address,
rn = ROW_NUMBER() OVER (PARTITION BY PersonID ORDER BY Address)
FROM dbo.tblAddress
)
SELECT PersonID, PersonName,[Address1],[Address2],[Address3] FROM
(
SELECT p.PersonID, p.PersonName,
[Address1] = x1.Address,
[Address2] = x2.Address,
[Address3] = x3.Address
FROM dbo.tblPerson AS p
LEFT OUTER JOIN xMaster AS x1 ON x1.PersonID = p.PersonID AND x1.rn = 1
LEFT OUTER JOIN xMaster AS x2 ON x2.PersonID = p.PersonID AND x2.rn = 2
LEFT OUTER JOIN xMaster AS x3 ON x3.PersonID = p.PersonID AND x3.rn = 3
) AS Addresses;
If you execute it, you will see this:
I know the query to get here is an ugly mess, but your requirement dictates it. It would be easier to return a comma-separated list as I suggested in my comment, or to have the presentation tier deal with the pivoting.