I have the following tables
BATCH
BatchID Name CustomerID DateCreated Status
12 A 1 01/01/2013 Active
13 B 12 01/01/2013 Inactive
14 C 245 01/01/2013 Complete
BATCHDETAIL
BatchDetailID BatchID Weight Price DestinationCode
1 12 55 500.00 99
2 12 119 1500.00 55
3 13 12 133 1212
A batch record can have many batch detail records linked via the FK BatchDetail.BatchID
I want to write a query to select a single row back to the user which combines the information in the BATCH record and the Weight,Price and DestinationCode from both BATCHDETAIL records for BatchID = 12
So the output would be :
BatchID Name CustomerID DateCreated Status WeightA PriceA DestinationCodeA WeightB PriceB DestinationCodeB
12 A 1 01/01/2013 Active 55 500.00 99 119 1500 55
So you can see I want to have 1 row with all information combined in the one row and differentiate each detail record with A or B ( Lets assume a maximum of 2 detail records is only allowed )
I have thought of creating a table with these fields and then building up the information in a series of select statements and finally doing a select on the temp table but getting the query into a single block of SQL would be ideal.
Here is a solution using dynamic SQL:
-- Get the MAX total number of records per BatchID (how many sets of columns do we need?)
DECLARE #requiredLevels int = (SELECT MAX(C) FROM (SELECT COUNT(*) C FROM BATCHDETAIL GROUP BY BatchID) Q)
;
-- Build a dynamic statement for the final SELECT fields
DECLARE
#finalFieldsSQL varchar(1000) = ''
, #finalFieldsN int = 1
;
WHILE #finalFieldsN <= #requiredLevels
BEGIN
SET #finalFieldsSQL = #finalFieldsSQL + ', Weight' + CHAR(64 + #finalFieldsN) + ', Price' + CHAR(64 + #finalFieldsN) + ', DestinationCode' + CHAR(64 + #finalFieldsN)
SET #finalFieldsN = #finalFieldsN + 1
END
-- Build a dynamic statement for the subquery SELECT fields
DECLARE
#subqueryFieldsSQL varchar(1000) = ''
, #subqueryFieldsN int = 1
;
WHILE #subqueryFieldsN <= #requiredLevels
BEGIN
SET #subqueryFieldsSQL = #subqueryFieldsSQL + ', MAX([' + CAST(#subqueryFieldsN AS varchar) + ']) ColumnName' + CHAR(64 + #subqueryFieldsN)
SET #subqueryFieldsN = #subqueryFieldsN + 1
END
-- Build a dynamic statement for the PIVOT fields
DECLARE
#pivotFieldsSQL varchar(1000) = ''
, #pivotFieldsN int = 1
;
WHILE #pivotFieldsN <= #requiredLevels
BEGIN
SET #pivotFieldsSQL = #pivotFieldsSQL + ', [' + CAST(#pivotFieldsN AS varchar) + ']'
SET #pivotFieldsN = #pivotFieldsN + 1
END
SET #pivotFieldsSQL = SUBSTRING(#pivotFieldsSQL, 3, LEN(#pivotFieldsSQL) - 2)
-- Build the final SQL statement and execute
DECLARE #SQL varchar(8000) =
'
SELECT
B.BatchID, B.Name, B.CustomerID, B.DateCreated, [Status]' + #finalFieldsSQL + '
FROM
BATCH B
LEFT JOIN
(
SELECT
BatchID' + REPLACE(#subqueryFieldsSQL, 'ColumnName', 'Weight') + '
FROM
(
SELECT BD.BatchID, [Weight], ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
FROM
BATCH B
JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
) Q
PIVOT
(
MAX([Weight])
FOR R IN (' + #pivotFieldsSQL + ')
) P
GROUP BY BatchID
) W
ON B.BatchID = W.BatchID
LEFT JOIN
(
SELECT
BatchID' + REPLACE(#subqueryFieldsSQL, 'ColumnName', 'Price') + '
FROM
(
SELECT BD.BatchID, Price, ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
FROM
BATCH B
JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
) Q
PIVOT
(
MAX(Price)
FOR R IN (' + #pivotFieldsSQL + ')
) P
GROUP BY BatchID
) P
ON B.BatchID = P.BatchID
LEFT JOIN
(
SELECT
BatchID' + REPLACE(#subqueryFieldsSQL, 'ColumnName', 'DestinationCode') + '
FROM
(
SELECT BD.BatchID, DestinationCode, ROW_NUMBER() OVER (PARTITION BY B.BatchID ORDER BY BatchDetailID) R
FROM
BATCH B
JOIN BATCHDETAIL BD ON B.BatchID = BD.BatchID
) Q
PIVOT
(
MAX(DestinationCode)
FOR R IN (' + #pivotFieldsSQL + ')
) P
GROUP BY BatchID
) D
ON B.BatchID = D.BatchID
'
EXEC (#SQL)
If you don't want to show empty records, replace LEFT JOIN with JOIN in the final statement (3 occurences).
you can use Pivot and UnPivot to achieve this result. Try Something like this:
SELECT
BatchID,[Name],[CustomerID],[DateCreated],[Status],
MAX(Weight1) as WeightA,
MAX(Price1) as PriceA,
MAX(DestinationCode1) as DestinationCodeA,
MAX(Weight2) as WeightB,
MAX(Price2) as PriceB,
MAX(DestinationCode2) as DestinationCodeB
FROM (
SELECT *,COL + CAST(DENSE_RANK() OVER (PARTITION BY Batchid ORDER BY BatchDetailID ASC) AS VARCHAR) AS BATCHPIVOT
FROM
(
SELECT b.*,cast(d.Weight as varchar(255)) as Weight, cast(d.Price as varchar(255)) as Price, cast(d.DestinationCode as varchar(255)) as DestinationCode,d.BatchDetailID
FROM #Batch B
INNER JOIN #BATCHDETAIL D on b.BatchID = d.BatchID
) AS cp
UNPIVOT
(
Val FOR Col IN ([Weight], [Price], [DestinationCode])
) AS up
) AS query
PIVOT (MAX(Val)
FOR BATCHPIVOT IN (Weight1,Price1,DestinationCode1, Weight2, Price2, DestinationCode2)) AS Pivot1
GROUP BY BatchID,[Name],[CustomerID],[DateCreated],[Status]
This is just standard query. you can make this script Dynamic according to your liking:
Complete Script:
Create table #Batch
(BatchID int,
[Name] char(1),
[CustomerID] int,
[DateCreated] date,
[Status] varchar(50)
)
Create table #BATCHDETAIL
(BatchDetailID int,
BatchID int,
[Weight] int,
Price money,
DestinationCode int
)
INSERT INTO #Batch
VALUES(12,'A',1,'01/01/2013','Active')
,(13,'B',12,'01/01/2013','Inactive')
,(14,'C',245,'01/01/2013','Complete')
INSERT INTO #BATCHDETAIL
VALUES(1,12,55,500.00,99)
,(2,12,119,1500.00,55)
,(3,13,12,133,1212)
SELECT
BatchID,[Name],[CustomerID],[DateCreated],[Status],
MAX(Weight1) as WeightA,
MAX(Price1) as PriceA,
MAX(DestinationCode1) as DestinationCodeA,
MAX(Weight2) as WeightB,
MAX(Price2) as PriceB,
MAX(DestinationCode2) as DestinationCodeB
FROM (
SELECT *,COL + CAST(DENSE_RANK() OVER (PARTITION BY Batchid ORDER BY BatchDetailID ASC) AS VARCHAR) AS BATCHPIVOT
FROM
(
SELECT b.*,cast(d.Weight as varchar(255)) as Weight, cast(d.Price as varchar(255)) as Price, cast(d.DestinationCode as varchar(255)) as DestinationCode,d.BatchDetailID
FROM #Batch B
INNER JOIN #BATCHDETAIL D on b.BatchID = d.BatchID
) AS cp
UNPIVOT
(
Val FOR Col IN ([Weight], [Price], [DestinationCode])
) AS up
) AS query
PIVOT (MAX(Val)
FOR BATCHPIVOT IN (Weight1,Price1,DestinationCode1, Weight2, Price2, DestinationCode2)) AS Pivot1
GROUP BY BatchID,[Name],[CustomerID],[DateCreated],[Status]
I am new to ssrs.
I want to get all the possible data for ssrs subscribed report, which are Available in ResportServer database.
I have found some queries, but that does not have proper data. It only works for single report.
I need list of unique subscription with it's data. If possible stored procedure is preferable.
My query:
SELECT
b.name AS JobName
, e.name
, e.path
, d.description
, a.SubscriptionID
, laststatus
, eventtype
, LastRunTime
, date_created
, date_modified
FROM ReportServer.dbo.ReportSchedule a
JOIN msdb.dbo.sysjobs b
ON a.ScheduleID = b.name
JOIN ReportServer.dbo.ReportSchedule c
ON b.name = c.ScheduleID
JOIN ReportServer.dbo.Subscriptions d
ON c.SubscriptionID = d.SubscriptionID
JOIN ReportServer.dbo.Catalog e
ON d.report_oid = e.itemid
WHERE e.name = 'Sales_Report'
Thanks in advance.
I have same requirement once as like you have now...
See below stored procedure..
CREATE PROCEDURE [dbo].[GetSubscriptionData]
AS
BEGIN
SET NOCOUNT ON;
WITH
[Sub_Parameters] AS
(
SELECT [SubscriptionID], [Parameters] = CONVERT(XML,a.[Parameters])
FROM [Subscriptions] a
),
[MySubscriptions] AS
(
SELECT DISTINCT [SubscriptionID], [ParameterName] = QUOTENAME(p.value('(Name)[1]', 'nvarchar(max)')), [ParameterValue] = p.value('(Value)[1]', 'nvarchar(max)')
FROM [Sub_Parameters] a
CROSS APPLY [Parameters].nodes('/ParameterValues/ParameterValue') t(p)
),
[SubscriptionsAnalysis] AS
(
SELECT a.[SubscriptionID], a.[ParameterName], [ParameterValue] =
(
SELECT STUFF((SELECT [ParameterValue] + ', ' as [text()]
FROM [MySubscriptions]
WHERE [SubscriptionID] = a.[SubscriptionID] AND [ParameterName] = a.[ParameterName]
FOR XML PATH('') ),1, 0, '') +''
)
FROM [MySubscriptions] a
GROUP BY a.[SubscriptionID],a.[ParameterName]
)
SELECT
DISTINCT (a.[SubscriptionID]),
c.[UserName] AS Owner,
b.Name,
b.Path,
a.[Locale],
a.[InactiveFlags],
d.[UserName] AS Modified_by,
a.[ModifiedDate],
a.[Description],
a.[LastStatus],
a.[EventType],
a.[LastRunTime],
a.[DeliveryExtension],
a.[Version],
sch.StartDate,
--e.[ParameterName],
--LEFT(e.[ParameterValue],LEN(e.[ParameterValue])-1) as [ParameterValue],
SUBSTRING(b.PATH,2,LEN(b.PATH)-(CHARINDEX('/',REVERSE(b.PATH))+1)) AS ProjectName
FROM
[Subscriptions] a
INNER JOIN [Catalog] AS b ON a.[Report_OID] = b.[ItemID]
Inner Join ReportSchedule as RS on rs.SubscriptionID = a.SubscriptionID
INNER JOIN Schedule AS Sch ON Sch.ScheduleID = rs.ScheduleID
LEFT OUTER JOIN [Users] AS c ON a.[OwnerID] = c.[UserID]
LEFT OUTER JOIN [Users] AS d ON a.MODIFIEDBYID = d.Userid
LEFT OUTER JOIN [SubscriptionsAnalysis] AS e ON a.SubscriptionID = e.SubscriptionID;
END
This is simplified query to get all SSRS Subscriptions
SELECT USR.UserName AS SubscriptionOwner
,SUB.ModifiedDate
,SUB.[Description]
,SUB.EventType
,SUB.DeliveryExtension
,SUB.LastStatus
,SUB.LastRunTime
,SCH.NextRunTime
,SCH.Name AS ScheduleName
,CAT.[Path] AS ReportPath
,CAT.[Description] AS ReportDescription
FROM dbo.Subscriptions AS SUB
INNER JOIN dbo.Users AS USR
ON SUB.OwnerID = USR.UserID
INNER JOIN dbo.[Catalog] AS CAT
ON SUB.Report_OID = CAT.ItemID
INNER JOIN dbo.ReportSchedule AS RS
ON SUB.Report_OID = RS.ReportID
AND SUB.SubscriptionID = RS.SubscriptionID
INNER JOIN dbo.Schedule AS SCH
ON RS.ScheduleID = SCH.ScheduleID
ORDER BY USR.UserName, CAT.[Path];
if you still have any query, comment it..
In case you need to find the sql server agent Job use this updated code
SET NOCOUNT ON;
WITH
[Sub_Parameters] AS
(
SELECT [SubscriptionID], [Parameters] = CONVERT(XML,a.[Parameters])
FROM [Subscriptions] a
),
[MySubscriptions] AS
(
SELECT DISTINCT [SubscriptionID], [ParameterName] = QUOTENAME(p.value('(Name)[1]', 'nvarchar(max)')), [ParameterValue] = p.value('(Value)[1]', 'nvarchar(max)')
FROM [Sub_Parameters] a
CROSS APPLY [Parameters].nodes('/ParameterValues/ParameterValue') t(p)
),
[SubscriptionsAnalysis] AS
(
SELECT a.[SubscriptionID], a.[ParameterName], [ParameterValue] =
(
SELECT STUFF((SELECT [ParameterValue] + ', ' as [text()]
FROM [MySubscriptions]
WHERE [SubscriptionID] = a.[SubscriptionID] AND [ParameterName] = a.[ParameterName]
FOR XML PATH('') ),1, 0, '') +''
)
FROM [MySubscriptions] a
GROUP BY a.[SubscriptionID],a.[ParameterName]
)
SELECT
DISTINCT (a.[SubscriptionID]),
j.name AS SQLServerAgentJob,
c.[UserName] AS Owner,
b.Name,
b.Path,
a.[Locale],
a.[InactiveFlags],
d.[UserName] AS Modified_by,
a.[ModifiedDate],
a.[Description],
a.[LastStatus],
a.[EventType],
a.[LastRunTime],
a.[DeliveryExtension],
a.[Version],
sch.StartDate,
--e.[ParameterName],
--LEFT(e.[ParameterValue],LEN(e.[ParameterValue])-1) as [ParameterValue],
SUBSTRING(b.PATH,2,LEN(b.PATH)-(CHARINDEX('/',REVERSE(b.PATH))+1)) AS ProjectName
FROM [Subscriptions] a
INNER JOIN [Catalog] AS b ON a.[Report_OID] = b.[ItemID]
Inner Join ReportSchedule as RS on rs.SubscriptionID = a.SubscriptionID
INNER JOIN Schedule AS Sch ON Sch.ScheduleID = rs.ScheduleID
LEFT OUTER JOIN [Users] AS c ON a.[OwnerID] = c.[UserID]
LEFT OUTER JOIN [Users] AS d ON a.MODIFIEDBYID = d.Userid
LEFT OUTER JOIN [SubscriptionsAnalysis] AS e ON a.SubscriptionID = e.SubscriptionID
LEFT JOIN msdb.dbo.sysobjects so ON rs.ScheduleID= so.name
INNER JOIN msdb.dbo.sysjobs J ON CONVERT( NVARCHAR(128), RS.ScheduleID ) = J.name
INNER JOIN msdb.dbo.sysjobschedules JS ON J.job_id = JS.job_id
I am using following query to get subscriptions and then to find SQL Jobs scripts
USE ReportServer
GO
CREATE TABLE #tempReports(LogEntryId BIGINT, subscriptionid VARCHAR(1000),LastRunTime DATETIME, _Description VARCHAR(1000), ReportID VARCHAR(1000),
LastStatus VARCHAR(1000), rowNum INT)
INSERT INTO #tempReports
SELECT *
FROM
(
SELECT DISTINCT E.LogEntryId, S.subscriptionid, LastRunTime, S.Description, E.ReportID, S.LastStatus,
ROW_NUMBER() OVER(PARTITION BY E.ReportID, S.Description ORDER BY S.LastRunTime DESC) as rowNum
FROM [ExecutionLogStorage] E
INNER JOIN Subscriptions S
ON S.Report_OID = E.ReportID
WHERE 1 = 1
AND (
S.LastStatus LIKE '%has been saved to the "\\<server>\c$\SSRS_Report_Export\20%'
)
)T
WHERE rowNum = 1
ORDER BY ReportID, Description
CREATE TABLE #ExecutionStatements (ExecStatement VARCHAR(1000), job_name VARCHAR(1000), theReportOrder INT,
LogEntryId BIGINT, subscriptionid VARCHAR(1000), LastRunTime DATETIME, _Description VARCHAR(1000),
ReportID VARCHAR(1000), LastStatus VARCHAR(1000))
INSERT INTO #ExecutionStatements
SELECT 'exec sp_start_job #job_name = ''' + cast(j.name as varchar(40)) + '''' AS ExecStatement,
j.name AS job_name,
ROW_NUMBER () OVER(ORDER BY LogEntryId) AS theReportOrder,
LogEntryId, subscriptionid,LastRunTime, _Description, ReportID,
LastStatus
from msdb.dbo.sysjobs j
join msdb.dbo.sysjobsteps js
on js.job_id = j.job_id
join #tempReports s
on js.command like '%' + cast(s.subscriptionid as varchar(40)) + '%'
WHERE 1 = 1
---Execute required statements in MSDB
SELECT E.ExecStatement + '--'+ CONVERT(VARCHAR(10),E.theReportOrder), E.theReportOrder, *
FROM #ExecutionStatements E
--WHERE subscriptionid = '3AFDAC30-4F30-423F-9F72-7C04C86026AB'
ORDER BY E.theReportOrder
SELECT DISTINCT S.subscriptionid, S.Description, E.ReportID, S.LastStatus, MAX(LastRunTime) -- 2021-04-25 18:35:00.840
FROM [ExecutionLogStorage] E
INNER JOIN Subscriptions S
ON S.Report_OID = E.ReportID
WHERE S.subscriptionid = '3AFDAC30-4F30-423F-9F72-7C04C86026AB'
GROUP BY S.subscriptionid, S.Description, E.ReportID, S.LastStatus
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
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.