Left join with view taking too much time in SQL Server - sql-server-2012

This query is taking twenty seconds to display 53,000 records. This query has five left joins with views. But when I comment out the column MAN.F_PHR AS MANU in the select statement, it takes three seconds to display the 53,000 records.
How can I optimize this query? The view V_PROD_ALIAS_MANU MAN contains two left joins. The MAN.F_PHRE AS MANU column is from the view. Is there any way to optimize this query?
SELECT DISTINCT
TP.PRODUCT AS ID,
TP.NAME AS [NAME],
TP.LANGUAGE AS LANGCODE,
CONVERT(VARCHAR,TP.F_DATE_REVISED,120) AS RDATE,
CASE
WHEN NOT(REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUM,'¿',' '))),' ','; ') IS NULL OR REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUM,'¿',' '))),' ','; ') = '')
THEN REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUM,'¿',' '))),' ','; ')
ELSE REPLACE(LTRIM(RTRIM(REPLACE(CASN.F_DATA,'¿',' '))),' ','; ')
END AS CASNUM ,
TP.F_CUSTOM1 AS cus1,
TP.F_CUSTOM2 AS cus2,
(SELECT TC.F_COUNTRY_NAME FROM COUNTRIES TC
WHERE TC.F_COUNTRY_CODE = TP.F_CUSTOM5) AS cus5,
MAN.F_PHR AS MANU,
CASE
WHEN NOT(TP.F_CUSTOM3 IS NULL OR TP.F_CUSTOM3 = '')
THEN TP.F_CUSTOM3
ELSE SYN.F_DATA
END AS SYN,
IC.F_DATA AS ICO,
'SDS - ' + (SELECT TL.F_LAN_NAME FROM T_LANGUAGE TL
WHERE TL.F_LANGUAGE = TP.F_LANGUAGE) + ' - PDF' AS DOC,
'' AS COVER,
CAST(TP.F_GUID AS VARCHAR(36)) + '_PDF' AS [GUID],
'PDF' AS SDS
FROM
PDF TP
LEFT JOIN
V_PROD_ALIAS_SYN SYN ON TP.F_PRODUCT = SYN.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_SITE SIT ON TP.F_PRODUCT = SIT.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_ICO IC ON TP.F_PRODUCT = IC.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_MANU MAN ON TP.F_PRODUCT = MAN.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_CASN CASN ON TP.F_PRODUCT = CASN.F_PRODUCT
Query after commenting out the column MAN.F_PHRE AS MANU takes three seconds to display 53,000 records.
SELECT DISTINCT
TP.PRODUCT AS ID,
TP.NAME AS [NAME],
TP.LANGUAGE AS LANGCODE,
CONVERT(VARCHAR, TP.F_DATE_REVISED, 120) AS RDATE,
CASE
WHEN NOT(REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUM,'¿',' '))),' ','; ') IS NULL OR REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUM,'¿',' '))),' ','; ') = '')
THEN REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUM,'¿',' '))),' ','; ')
ELSE REPLACE(LTRIM(RTRIM(REPLACE(CASN.F_DATA,'¿',' '))),' ','; ')
END AS CASNUM ,
TP.F_CUSTOM1 AS cus1,
TP.F_CUSTOM2 AS cus2,
(SELECT TC.F_COUNTRY_NAME FROM COUNTRIES TC
WHERE TC.F_COUNTRY_CODE = TP.F_CUSTOM5) AS cus5,
-- MAN.F_PHR AS MANU,
CASE
WHEN NOT(TP.F_CUSTOM3 IS NULL OR TP.F_CUSTOM3 = '')
THEN TP.F_CUSTOM3
ELSE SYN.F_DATA
END AS SYN,
IC.F_DATA AS ICO,
'SDS - ' + (SELECT TL.F_LAN_NAME FROM T_LANGUAGE TL
WHERE TL.F_LANGUAGE = TP.F_LANGUAGE) + ' - PDF' AS DOC,
'' AS COVER,
CAST(TP.F_GUID AS VARCHAR(36)) + '_PDF' AS [GUID],
'PDF' AS SDS
FROM
PDF TP
LEFT JOIN
V_PROD_ALIAS_SYN SYN ON TP.F_PRODUCT = SYN.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_SITE SIT ON TP.F_PRODUCT = SIT.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_ICO IC ON TP.F_PRODUCT = IC.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_MANU MAN ON TP.F_PRODUCT = MAN.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_CASN CASN ON TP.F_PRODUCT = CASN.F_PRODUCT

Related

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

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/

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

Create dynamic column in SQL as VARCHAR MAX

I am using a standard SQL query to determine where indexes are needed however one of the columns which gives you the TSQL to build the index is getting cutoff because there are so many fields in the index. The columns themselves also appear cutoff. How do I modify it so CreateIndexStatement is a VARCHAR MAX which doesn't get cutoff:
SELECT sys.objects.name
, (avg_total_user_cost * avg_user_impact) * (user_seeks + user_scans) AS Impact
, 'CREATE NONCLUSTERED INDEX ix_IndexName ON ' + sys.objects.name COLLATE DATABASE_DEFAULT + ' ( ' + IsNull(mid.equality_columns, '') + CASE WHEN mid.inequality_columns IS NULL
THEN ''
ELSE CASE WHEN mid.equality_columns IS NULL
THEN ''
ELSE ',' END + mid.inequality_columns END + ' ) ' + CASE WHEN mid.included_columns IS NULL
THEN ''
ELSE 'INCLUDE (' + mid.included_columns + ')' END + ';' AS CreateIndexStatement
, mid.equality_columns
, mid.inequality_columns
, mid.included_columns
FROM sys.dm_db_missing_index_group_stats AS migs
INNER JOIN sys.dm_db_missing_index_groups AS mig ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid ON mig.index_handle = mid.index_handle AND mid.database_id = DB_ID()
INNER JOIN sys.objects WITH (nolock) ON mid.OBJECT_ID = sys.objects.OBJECT_ID
WHERE (migs.group_handle IN
(
SELECT TOP (500) group_handle
FROM sys.dm_db_missing_index_group_stats WITH (nolock)
ORDER BY (avg_total_user_cost * avg_user_impact) * (user_seeks + user_scans) DESC))
AND OBJECTPROPERTY(sys.objects.OBJECT_ID, 'isusertable')=1
ORDER BY 2 DESC , 3 DESC
Just cast the first column in the list as a varchar(max)
SELECT cast(ColumnA as varchar(max))
+ ColumnB + ColumnC + .... + ColumnZ AS SomeColumn
FROM SomeTable

SQL Server T-SQL not returning results with no error - this should work right?

I am trying to find something that does not match in 2 tables, this should be easy, now this works fine.
Select *
from Shop_Import SI
where SI.productID not in (SELECT productref FROM Shop_Import_Cats)
But this is the SQL I need to use, but it just does not return the 1 result that the above does:
SELECT
'Insert into Shop_Import_Cats values ('
+ CAST(p.ProductID AS VARCHAR) + ','
+ CAST(c.CategoryID AS VARCHAR) + ','
+ CAST(SI.ProductID AS VARCHAR) + ',getdate())
FROM
NB_Store_Products p
JOIN
NB_Store_ProductLang pl ON p.ProductID = pl.ProductID
JOIN
Shop_Import SI ON p.ProductRef = SI.ProductID
JOIN
NB_Store_CategoryLang CL ON SI.Primary_Category = CL.CategoryName
JOIN
NB_Store_Categories C ON CL.CategoryID = C.CategoryID
JOIN
Shop_Import_Cats SIC ON SI.ProductID = SIC.productref
WHERE
SI.ProductID NOT IN (SELECT SIC.productref
FROM Shop_Import_Cats SIC)
Based on advice here I tried this swapping the tables around and left joins to no avail - it returns null but should return one result.
Select 'Insert into Shop_Import_Cats values (' + CAST(p.ProductID as varchar) + ',' + CAST(c.CategoryID as varchar) + ',' + CAST(SI.ProductID as varchar) + ',getdate())'
from Shop_Import SI
left join NB_Store_Products P on SI.ProductID=p.ProductRef
left join NB_Store_ProductLang pl on p.ProductID=pl.ProductID
left join NB_Store_CategoryLang CL on SI.Primary_Category=CL.CategoryName
left join NB_Store_Categories C on CL.CategoryID=C.CategoryID
left join Shop_Import_Cats SIC on SI.ProductID=SIC.productref
where SI.ProductID not in (SELECT SIC.productref FROM Shop_Import_Cats SIC)
What am I doing wrong?
Try this instead:
SELECT
'Insert into Shop_Import_Cats values ('
+ CAST(coalesce(p.ProductID,' ') AS VARCHAR) + ','
+ CAST(coalesce(c.CategoryID,' ') AS VARCHAR) + ','
+ CAST(coalesce(SI.ProductID,' ') AS VARCHAR) + ',getdate())
from (
select
ProductID,
Primary_Category
/* insert any additional required columnx here */
from Shop_Import SI
where SI.ProductID not in (SELECT SIC.productref FROM Shop_Import_Cats SIC)
) SI
left join NB_Store_Products P on SI.ProductID = p.ProductRef
left join NB_Store_ProductLang pl on p.ProductID = pl.ProductID
left join NB_Store_CategoryLang CL on SI.Primary_Category = CL.CategoryName
left join NB_Store_Categories C on CL.CategoryID = C.CategoryID
left join Shop_Import_Cats SIC on SI.ProductID = SIC.productref
Now the WHERE condition will be executed on the same relvar as in the working example. I suspect that a null value is invoking 3-valued logic and propagating an UNKNOWN into a null record-set.
** edit Needed to add the SI to the 'from Shop_Import'
You just need to remove Shop_import_cats from the join:
Select 'Insert into Shop_Import_Cats values (' + CAST(p.ProductID as varchar) + ',' + CAST(c.CategoryID as varchar) + ',' + CAST(SI.ProductID as varchar) + ',getdate())'
from Shop_Import SI
left join NB_Store_Products P on SI.ProductID=p.ProductRef
left join NB_Store_ProductLang pl on p.ProductID=pl.ProductID
left join NB_Store_CategoryLang CL on SI.Primary_Category=CL.CategoryName
left join NB_Store_Categories C on CL.CategoryID=C.CategoryID
where SI.ProductID not in (SELECT SIC.productref FROM Shop_Import_Cats SIC)

Pivot table giving wrong result

Below code gives me result set as shown in first image
SELECT dbo.tbStudent.Name, dbo.tbStudent.RegNo, dbo.tbFee.PID, dbo.tbFee.Purpose, dbo.tbFee.AmountPaid, dbo.tbFee.StudentID, dbo.tbFee.Date, dbo.tbFee.FeeID,
dbo.tbFee.SemID, dbo.tbFee.CourseID, dbo.tbFee.ModeOfPayment, dbo.tbFee.CheckNo, dbo.tbFee.DDNo, dbo.tbFee.HostelDDNo, dbo.tbFee.FRID,
dbo.tbStudent.Parentage, dbo.tbCourse.Name AS Course, ISNULL(dbo.tbSemester.SemName, ' + #st +') AS Semester
FROM dbo.tbFee INNER JOIN
dbo.tbStudent ON dbo.tbFee.StudentID = dbo.tbStudent.StudentID INNER JOIN
dbo.tbCourse ON dbo.tbFee.CourseID = dbo.tbCourse.CourseID LEFT OUTER JOIN
dbo.tbSemester ON dbo.tbFee.SemID = dbo.tbSemester.SemID Where tbFee.SemID=1
However using Pivot table I need result as below:
My code for pivot table is :
SET #values = '';
If(#SemID=0)
BEGIN
SELECT #values = #values +'['+ CAST(PurPose AS varchar(max))+ ']' + ','
FROM tbFee Where CourseID=#CourseID
SET #values = SUBSTRING(#values, 1, Len(#values) - 1)
END
ELSE
BEGIN
SELECT #values = #values +'['+ CAST(PurPose AS varchar(max))+ ']' + ','
FROM tbFee Where SemID=#SemID
SET #values = SUBSTRING(#values, 1, Len(#values) - 1)
END
Declare #st nvarchar(max)
set #st='''Not Available''';
declare #q nvarchar(max)
set #q = '
Select * from(
SELECT dbo.tbStudent.Name, dbo.tbStudent.RegNo, dbo.tbFee.PID, dbo.tbFee.Purpose, dbo.tbFee.AmountPaid, dbo.tbFee.StudentID, dbo.tbFee.Date, dbo.tbFee.FeeID,
dbo.tbFee.SemID, dbo.tbFee.CourseID, dbo.tbFee.ModeOfPayment, dbo.tbFee.CheckNo, dbo.tbFee.DDNo, dbo.tbFee.HostelDDNo, dbo.tbFee.FRID,
dbo.tbStudent.Parentage, dbo.tbCourse.Name AS Course, ISNULL(dbo.tbSemester.SemName, ' + #st +') AS Semester
FROM dbo.tbFee INNER JOIN
dbo.tbStudent ON dbo.tbFee.StudentID = dbo.tbStudent.StudentID INNER JOIN
dbo.tbCourse ON dbo.tbFee.CourseID = dbo.tbCourse.CourseID LEFT OUTER JOIN
dbo.tbSemester ON dbo.tbFee.SemID = dbo.tbSemester.SemID Where tbFee.SemID=1
) as x
pivot (
max(AmountPaid)
for Purpose in (' + #values + ')
) as pvt
'
exec (#q)
I am getting Values of Purpose columns in #values due to the reason that number of rows can change. However instead of getting result as single row for same student having same regNo , I am getting below result :
But what I am getting is below:
In the source query for your PIVOT, you should only specify those columns which are involved in the actual pivot - namely dbo.tbStudent.Name, dbo.tbStudent.RegNo, dbo.tbFee.Purpose, dbo.tbFee.AmountPaid.
SELECT
dbo.tbStudent.Name,
dbo.tbStudent.RegNo,
dbo.tbFee.Purpose,
dbo.tbFee.AmountPaid
FROM
dbo.tbFee
INNER JOIN dbo.tbStudent ON dbo.tbFee.StudentID = dbo.tbStudent.StudentID
INNER JOIN dbo.tbCourse ON dbo.tbFee.CourseID = dbo.tbCourse.CourseID
LEFT OUTER JOIN dbo.tbSemester ON dbo.tbFee.SemID = dbo.tbSemester.SemID
Where tbFee.SemID=1
If any other columns apart from these are present, they will be factored into the pivot computation, and you will get multiple rows accordingly.