Hard Query with SqlServer (with When and else) - sql-server

i have a query but i don't know why it is bad.
The error is: SQL (4104): Invalid column name 'CUSTOMDATA2' The multi-part identifier "PCO.QUALIFICATIONCODE.code" could not be bound, but i don't uderstand where and why it is bad.
I am very lost with this query :/, some guru of querys can i help me ?.
Edited query for dont hurt people.
Thank you in advance.
SELECT PCO_QUALIFICATIONCODE.CODE,
CASE
WHEN (ActividadesActivas.[CUSTOMDATA2] IS NULL)
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE BIS
WHERE SERVICEID = 1
AND BIS.CODE = SUBSTRING(CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR), 1, 3)
)
ELSE ActividadesActivas.[CUSTOMDATA2]
END CUSTOMDATA2,
CASE
WHEN (ActividadesActivas.[CUSTOMDATA3] IS NULL)
THEN
CASE
WHEN (SUBSTRING(CAST(CODE AS VARCHAR), 5, 1) <> '')
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE BIS
WHERE SERVICEID = 1
AND BIS.CODE = SUBSTRING(CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR), 1, 5)
)
WHEN (SUBSTRING(CAST(CODE AS VARCHAR), 4, 1) <> '')
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE BIS
WHERE SERVICEID = 1
AND BIS.CODE = SUBSTRING(CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR), 1, 4)
)
WHEN ActividadesActivas.[CUSTOMDATA3] IS NULL
OR ActividadesActivas.[CUSTOMDATA3] = 'NULL'
THEN ''
ELSE ActividadesActivas.[CUSTOMDATA3]
END
ELSE ActividadesActivas.[CUSTOMDATA3]
END CUSTOMDATA3,
Totales.TOTAL
FROM [SQLPR1].[PREP].PCO_QUALIFICATIONCODE
LEFT JOIN
(SELECT [QCODE],
CASE
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) = '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) <> '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
END CUSTOMDATA2,
CASE
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) = '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
CASE
WHEN CUSTOMDATA3 IS NULL
OR CUSTOMDATA3 = 'NULL'
THEN ''
ELSE CUSTOMDATA3
END
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) <> '') )
THEN
CASE
WHEN (SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)) IS NOT NULL
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)
) + ' / ' +
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 5)
)
ELSE
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 5)
)
END
ELSE ''
END CUSTOMDATA3
FROM [SQLPR1].[PREP].[PCO_INBOUNDLOG]
WHERE SERVICEID = 1
AND QCODE > 9
GROUP BY QCODE,
CUSTOMDATA2,
CUSTOMDATA3
) ActividadesActivas
ON PCO_QUALIFICATIONCODE.CODE = ActividadesActivas.QCODE
LEFT JOIN
(SELECT [QCODE],
CASE
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) = '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) <> '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
END CUSTOMDATA2,
CASE
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) = '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
CASE
WHEN CUSTOMDATA3 IS NULL
OR CUSTOMDATA3 = 'NULL'
THEN ''
ELSE CUSTOMDATA3
END
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) <> '') )
THEN
CASE
WHEN (SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)) IS NOT NULL
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)
) + ' / ' +
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 5)
)
ELSE
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 5)
)
END
ELSE ''
END CUSTOMDATA3,
COUNT(*) TOTAL
FROM [SQLPR1].[PREP].[PCO_INBOUNDLOG]
WHERE [SERVICEID] = 1
AND RDATE BETWEEN '2017/02/01 00:00:00' AND '2018/02/20 23:59:59'
GROUP BY QCODE,
CUSTOMDATA2,
CUSTOMDATA3
) Totales
ON ActividadesActivas.QCODE = Totales.QCODE
AND ActividadesActivas.CUSTOMDATA2 = Totales.CUSTOMDATA2
AND ActividadesActivas.CUSTOMDATA3 = Totales.CUSTOMDATA3
WHERE SERVICEID = 1
AND PCO_QUALIFICATIONCODE.CODE NOT IN (102,103,104,105,106,107,113)
GROUP BY PCO_QUALIFICATIONCODE.CODE,
ActividadesActivas.CUSTOMDATA2,
ActividadesActivas.CUSTOMDATA3,
Totales.TOTAL
ORDER BY CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR),
CUSTOMDATA2

Your problem here is in the group by.
You are masking your field "ActividadesActivas.[CUSTOMDATA2]" with "CUSTOMDATA2"
CASE
WHEN (ActividadesActivas.[CUSTOMDATA2] IS NULL)
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE BIS
WHERE SERVICEID = 1
AND BIS.CODE = SUBSTRING(CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR), 1, 3)
)
ELSE ActividadesActivas.[CUSTOMDATA2]
END CUSTOMDATA2,
so, in the group by, you can only use "CUSTOMDATA2" and not "ActividadesActivas.[CUSTOMDATA2]"
GROUP BY PCO_QUALIFICATIONCODE.CODE,
ActividadesActivas.CUSTOMDATA2,
ActividadesActivas.CUSTOMDATA3,
Totales.TOTAL
PS: same rule should apply to remaining fields.
EDIT: I'm not sure if that is the only issue with your query, but that is the reason for your issue "Invalid column name 'CUSTOMDATA2'"

Related

How to create view from the given set of code

I have never come across such a large amount of code and I want to make a View with exact same output that my SQL query is generating. The code is exceeding the limit hence I have reduced the code though the code is incomplete but I have tried making view by create view view name but I am unable to make.
I have tried create view view_name as (sql query) but its showing error:
incorrect syntax 'declare'
But when run alone this whole SQL query we are getting result. Is declare part is the problem?
DECLARE #ClientCode VARCHAR(20);
SELECT #ClientCode = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'ClientCode';
DECLARE #NoOfColorsInDashboardGraphs VARCHAR(10);
SELECT #NoOfColorsInDashboardGraphs = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'NoOfColorsInDashboardGraphs';
DECLARE #TerminologyToNonCompliedCompletedTasks VARCHAR(50);
SELECT #TerminologyToNonCompliedCompletedTasks = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToNonCompliedCompletedTasks';
DECLARE #TerminologyToNonCompliedNonCompletedTasks VARCHAR(50);
SELECT #TerminologyToNonCompliedNonCompletedTasks = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToNonCompliedNonCompletedTasks';
DECLARE #DeviationFunctionality VARCHAR(50);
SELECT #DeviationFunctionality = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'DeviationFunctionality';
DECLARE #ShowPerformedOnDate VARCHAR(10);
SELECT #ShowPerformedOnDate = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'ShowPerformedOnDate';
DECLARE #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt VARCHAR(50);
SELECT #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt';
DECLARE #TerminologyToCompliedTasks VARCHAR(50);
SELECT #TerminologyToCompliedTasks = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToCompliedTasks';
DECLARE #TerminologyToPosingRiskTasks VARCHAR(50);
SELECT #TerminologyToPosingRiskTasks = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToPosingRiskTasks';
SELECT TL.OID,
E.EntityOID,
U.UnitOID,
D.DeptOID,
E.EntityName,
U.UnitName,
D.DeptName,
(CASE
WHEN ISNULL(LTRIM(RTRIM(U.ShortDesc)), '') = ''
THEN CONVERT(VARCHAR(50), UT.UnitTaskOID)
ELSE U.ShortDesc + '-' + CONVERT(VARCHAR(50), UT.UnitTaskOID)
END) AS 'UnitTaskWithDesc',
UT.[UnitTaskOID],
UT.[TaskOID],
T.LegislationOID,
T.CentralTaskOID,
L.LegislationCategoryOID,
C.LegislationCategory,
ISNULL(
(
SELECT C.CompanyCategory
FROM CompanyCategory C
WHERE C.CompanyCategoryOID = T.CompanyCategoryOID
), '-') CompanyCategory,
L.CentralState,
L.LegislationName,
T.Section_Rule_Regulation_Notification,
S.STATE_OID,
S.STATE_NAME,
T.[Title],
T.[PriorityOID],
P.Priority,
T.[FrequencyOID],
F.Frequency,
T.[Devices],
T.[Section_Rule_Regulation_Notification],
T.[Requirement_Apply],
T.[Task],
T.[Regulating_Authority],
T.[Consequences],
T.[Department],
TL.[Status] AS TaskStatus,
UT.PerformerUserOID,
D.DeptHeadOID,
ISNULL((UDFH.FIRST_NAME + ' ' + UDFH.LAST_NAME), '-') AS 'DeptHead',
UT.DeptSupervisorOID,
ISNULL((UDSup.FIRST_NAME + ' ' + UDSup.LAST_NAME), '-') AS 'Supervisor',
TL.PerformerUserOID AS 'PerformerUserOID_log',
ISNULL((UDPer.FIRST_NAME + ' ' + UDPer.LAST_NAME), '-') AS 'Performer',
ISNULL((UDComp.FIRST_NAME + ' ' + UDComp.LAST_NAME), '-') AS 'TaskCompletedBy',
dbo.FormatDate(#ClientCode, TL.ApproverDt) AS 'ApproverDt',
dbo.FormatDate(#ClientCode, TL.ReviewerDt) AS 'ReviewerDt',
dbo.FormatDate(#ClientCode, TL.SupervisorDt) AS 'SupervisorDt',
dbo.FormatDate(#ClientCode, TL.PerformerDt) AS 'PerformerDt',
CASE
WHEN #DeviationFunctionality = 'Yes'
THEN ISNULL(TL.Deviation, '-')
ELSE ''
END AS 'Deviation',
dbo.FormatDate(#ClientCode, TL.PerformedOnDt) AS 'PerformedOnDt',
dbo.FormatDate(#ClientCode, TL.CompletedDt) AS 'CompletedDt',
ISNULL(TL.Comments, '-') AS 'Comments',
ISNULL(TL.ActivationComment, '-') AS ActivationComment,
ISNULL(TL.ReasonForNonComp, '-') AS 'ReasonForNonComp',
ISNULL(TL.ActionTaken, '-') AS 'ActionTaken',
dbo.GetCompletionDate(#ClientCode, TL.CompletedDt, #ShowPerformedOnDate, #NoOfColorsInDashboardGraphs, TL.PerformedOnDt) AS 'Completed On',
dbo.GetCompletionComment(TL.ActivationComment, TL.Comments, TL.ReviewerComment, TL.CompletedDt, TL.ReviewerCommentDate, TL.PeriodFromDate, TL.PeriodToDate) AS 'CompletionComments',
'' AS UnitDeviceOID,
'' AS TaskDeviceOID,
'' AS 'lblUnitDeviceOIDDesc',
dbo.GetComplianceStatus(TL.[Status], CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.ApproverDt, 112)), CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.CompletedDt, 112)), #NoOfColorsInDashboardGraphs, #TerminologyToNonCompliedCompletedTasks, #TerminologyToNonCompliedNonCompletedTasks, CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.PerformedOnDt, 112)), #ShowPerformedOnDate, #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt, #TerminologyToCompliedTasks, #TerminologyToPosingRiskTasks) AS 'ComplianceStatus',
ISNULL(TblLOGTMakerChecker.ConditionalOID, 0) AS MKOID,
ISNULL(TCSV.TaskComplianceStatusValue, '-') AS TaskComplianceStatusValue,
ISNULL(TL.TaskComplianceStatusValueOID, 0) AS TaskComplianceStatusValueOID,
#NoOfColorsInDashboardGraphs AS 'NoOfColorsOnReport',
#TerminologyToNonCompliedCompletedTasks AS 'TerminologyToNonCompliedCompletedTask',
#TerminologyToNonCompliedNonCompletedTasks AS 'TerminologyToNonCompliedNonCompletedTask',
#ShowPerformedOnDate AS 'ShowPerformedOnDate',
#TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt AS 'TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt',
#TerminologyToCompliedTasks AS 'TerminologyToCompliedTasks',
(CASE
WHEN(
(
SELECT COUNT(*)
FROM UnitTaskDocs
WHERE UnitTaskOID = UT.UnitTaskOID
AND DueDateId = TL.OID
) > 0)
THEN 'Yes'
ELSE 'No'
END) AS 'DocumentUploaded',
dbo.FormatDate
(#ClientCode,
(
SELECT TOP 1 UPLOADED_DATE
FROM UnitTaskDocs
WHERE UnitTaskOID = UT.UnitTaskOID
AND DueDateId = TL.OID
ORDER BY 1 DESC
)
) AS 'DocUploadedDate',
'No' AS 'DocumentUploadLater',
TL.FeesPaid,
TL.PenaltyPaid,
TL.SecondSupervisorComment,
TL.SecondSupervisorCommentDate,
TL.ThirdSupervisorComment,
TL.ThirdSupervisorCommentDate,
'' AS TaskType,
'-' AS Region,
'-' AS SubRegion
FROM UnitTask UT
INNER JOIN Task T ON T.Task_OID = UT.TaskOID
INNER JOIN LegislationNames L ON L.LegislationOID = T.LegislationOID
INNER JOIN LegislationCategories C ON C.LegislationCategoryOID = L.LegislationCategoryOID
INNER JOIN [STATE] S ON S.STATE_OID = L.StateOID
INNER JOIN Dept D ON D.DeptOID = UT.PerformerDeptOID
INNER JOIN Units U ON U.UnitOID = UT.UnitOID
INNER JOIN Entity E ON E.EntityOID = U.EntityOID
INNER JOIN Priority P ON P.PriorityOID = T.PriorityOID
INNER JOIN Frequency F ON F.FrequencyOID = T.FrequencyOID
INNER JOIN ConditionalTaskLog TL ON TL.UnitTaskOID = UT.UnitTaskOID
LEFT OUTER JOIN ConditionalMakerChecker TblLOGTMakerChecker ON TL.OID = TblLOGTMakerChecker.ConditionalOID
AND TblLOGTMakerChecker.STATUS = 0
LEFT OUTER JOIN TaskComplianceStatusValue TCSV ON TL.TaskComplianceStatusValueOID = TCSV.OID
INNER JOIN LTGN_USER_DETAIL UDFH ON UDFH.USER_OID = D.DeptHeadOID
LEFT OUTER JOIN LTGN_USER_DETAIL UDSup ON UDSup.USER_OID = TL.DeptSupervisorOID
INNER JOIN LTGN_USER_DETAIL UDPer ON UDPer.USER_OID = TL.PerformerUserOID
LEFT OUTER JOIN LTGN_USER_DETAIL UDComp ON UDComp.USER_OID = TL.CompletedByUserOID
WHERE UT.[Status] = 'Active'
AND UT.TaskStatus = 'Assigned'
AND T.Devices = 'No'
AND T.Title <> 'Applicability'
AND L.LegislationCategoryOID NOT IN(117, 118, 119, 120, 121, 122, 123, 124, 125)
AND T.CentralTaskOID NOT IN
(
SELECT CentralTaskOID
FROM GroupTask
)
AND U.EntityOID IN(27, 25, 26, 24)
AND u.UnitOID = UT.UnitOID
AND ((TL.ReviewerDt >= '12/17/2019'
AND TL.ReviewerDt <= '03/17/2020'
AND TL.PerformerDt <= '03/17/2020')
OR (TL.CompletedDt BETWEEN '12/17/2019' AND '03/17/2020')
OR (TL.ApproverDt >= '12/17/2019'
AND TL.ApproverDt <= '03/17/2020'))
UNION ALL
SELECT TL.OID,
E.EntityOID,
U.UnitOID,
D.DeptOID,
E.EntityName,
U.UnitName,
D.DeptName,
(CASE
WHEN ISNULL(LTRIM(RTRIM(U.ShortDesc)), '') = ''
THEN CONVERT(VARCHAR(50), UT.UnitTaskOID)
ELSE U.ShortDesc + '-' + CONVERT(VARCHAR(50), UT.UnitTaskOID)
END) AS 'UnitTaskWithDesc',
UT.[UnitTaskOID],
UT.[TaskOID],
T.LegislationOID,
T.CentralTaskOID,
L.LegislationCategoryOID,
C.LegislationCategory,
ISNULL(
(
SELECT C.CompanyCategory
FROM CompanyCategory C
WHERE C.CompanyCategoryOID = T.CompanyCategoryOID
), '-') CompanyCategory,
L.CentralState,
L.LegislationName,
T.Section_Rule_Regulation_Notification,
S.STATE_OID,
S.STATE_NAME,
T.[Title],
T.[PriorityOID],
P.Priority,
T.[FrequencyOID],
F.Frequency,
T.[Devices],
T.[Section_Rule_Regulation_Notification],
T.[Requirement_Apply],
T.[Task],
T.[Regulating_Authority],
T.[Consequences],
T.[Department],
TL.[Status] AS TaskStatus,
UT.PerformerUserOID,
D.DeptHeadOID,
ISNULL((UDFH.FIRST_NAME + ' ' + UDFH.LAST_NAME), '-') AS 'DeptHead',
UT.DeptSupervisorOID,
ISNULL((UDSup.FIRST_NAME + ' ' + UDSup.LAST_NAME), '-') AS 'Supervisor',
TL.PerformerUserOID AS 'PerformerUserOID_log',
ISNULL((UDPer.FIRST_NAME + ' ' + UDPer.LAST_NAME), '-') AS 'Performer',
ISNULL((UDComp.FIRST_NAME + ' ' + UDComp.LAST_NAME), '-') AS 'TaskCompletedBy',
dbo.FormatDate(#ClientCode, TL.ApproverDt) AS 'ApproverDt',
dbo.FormatDate(#ClientCode, TL.ReviewerDt) AS 'ReviewerDt',
dbo.FormatDate(#ClientCode, TL.SupervisorDt) AS 'SupervisorDt',
dbo.FormatDate(#ClientCode, TL.PerformerDt) AS 'PerformerDt',
CASE
WHEN #DeviationFunctionality = 'Yes'
THEN ISNULL(TL.Deviation, '-')
ELSE ''
END AS 'Deviation',
dbo.FormatDate(#ClientCode, TL.PerformedOnDt) AS 'PerformedOnDt',
dbo.FormatDate(#ClientCode, TL.CompletedDt) AS 'CompletedDt',
ISNULL(TL.Comments, '-') AS 'Comments',
('-') AS 'ActivationComment',
ISNULL(TL.ReasonForNonComp, '-') AS 'ReasonForNonComp',
ISNULL(TL.ActionTaken, '-') AS 'ActionTaken',
dbo.GetCompletionDate(#ClientCode, TL.CompletedDt, #ShowPerformedOnDate, #NoOfColorsInDashboardGraphs, TL.PerformedOnDt) AS 'Completed On',
dbo.GetCompletionComment('', TL.Comments, TL.ReviewerComment, TL.CompletedDt, TL.ReviewerCommentDate, TL.PeriodFromDate, TL.PeriodToDate) AS 'CompletionComments',
'' AS UnitDeviceOID,
'' AS TaskDeviceOID,
'' AS 'lblUnitDeviceOIDDesc',
dbo.GetComplianceStatus(TL.[Status], CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.ApproverDt, 112)), CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.CompletedDt, 112)), #NoOfColorsInDashboardGraphs, #TerminologyToNonCompliedCompletedTasks, #TerminologyToNonCompliedNonCompletedTasks, CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.PerformedOnDt, 112)), #ShowPerformedOnDate, #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt, #TerminologyToCompliedTasks, #TerminologyToPosingRiskTasks) AS 'ComplianceStatus',
ISNULL(TblLOGTMakerChecker.RoutineTaskOID, 0) AS MKOID,
ISNULL(TCSV.TaskComplianceStatusValue, '-') AS TaskComplianceStatusValue,
ISNULL(TL.TaskComplianceStatusValueOID, 0) AS TaskComplianceStatusValueOID,
#NoOfColorsInDashboardGraphs AS 'NoOfColorsOnReport',
#TerminologyToNonCompliedCompletedTasks AS 'TerminologyToNonCompliedCompletedTask',
#TerminologyToNonCompliedNonCompletedTasks AS 'TerminologyToNonCompliedNonCompletedTask',
#ShowPerformedOnDate AS 'ShowPerformedOnDate',
#TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt AS 'TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt',
#TerminologyToCompliedTasks AS 'TerminologyToCompliedTasks',
(CASE
WHEN(
(
SELECT COUNT(*)
FROM UnitTaskDocs
WHERE UnitTaskOID = UT.UnitTaskOID
AND DueDateId = TL.OID
) > 0)
THEN 'Yes'
ELSE 'No'
END) AS 'DocumentUploaded',
dbo.FormatDate
(#ClientCode,
(
SELECT TOP 1 UPLOADED_DATE
FROM UnitTaskDocs
WHERE UnitTaskOID = UT.UnitTaskOID
AND DueDateId = TL.OID
ORDER BY 1 DESC
)
) AS 'DocUploadedDate',
(CASE
WHEN(
(
SELECT COUNT(*)
FROM UnitTaskDoc_Reminder
WHERE UnitTaskOID = UT.UnitTaskOID
AND RoutineTaskOID = TL.OID
) > 0)
THEN 'Yes'
ELSE 'No'
END) AS 'DocumentUploadLater',
TL.FeesPaid,
TL.PenaltyPaid,
TL.SecondSupervisorComment,
TL.SecondSupervisorCommentDate,
TL.ThirdSupervisorComment,
TL.ThirdSupervisorCommentDate,
'' AS TaskType,
'-' AS Region,
'-' AS SubRegion
FROM UnitTask UT
INNER JOIN Task T ON T.Task_OID = UT.TaskOID
INNER JOIN LegislationNames L ON L.LegislationOID = T.LegislationOID
INNER JOIN LegislationCategories C ON C.LegislationCategoryOID = L.LegislationCategoryOID
INNER JOIN [STATE] S ON S.STATE_OID = L.StateOID
INNER JOIN Dept D ON D.DeptOID = UT.PerformerDeptOID
INNER JOIN Units U ON U.UnitOID = UT.UnitOID
INNER JOIN Entity E ON E.EntityOID = U.EntityOID
INNER JOIN Priority P ON P.PriorityOID = T.PriorityOID
INNER JOIN Frequency F ON F.FrequencyOID = T.FrequencyOID
INNER JOIN RoutineTaskLog TL ON TL.UnitTaskOID = UT.UnitTaskOID
LEFT OUTER JOIN RoutineMakerChecker TblLOGTMakerChecker ON TL.OID = TblLOGTMakerChecker.RoutineTaskOID
AND TblLOGTMakerChecker.STATUS = 0
LEFT OUTER JOIN TaskComplianceStatusValue TCSV ON TL.TaskComplianceStatusValueOID = TCSV.OID
INNER JOIN LTGN_USER_DETAIL UDFH ON UDFH.USER_OID = D.DeptHeadOID
LEFT OUTER JOIN LTGN_USER_DETAIL UDSup ON UDSup.USER_OID = TL.DeptSupervisorOID
INNER JOIN LTGN_USER_DETAIL UDPer ON UDPer.USER_OID = TL.PerformerUserOID
LEFT OUTER JOIN LTGN_USER_DETAIL UDComp ON UDComp.USER_OID = TL.CompletedByUserOID
WHERE UT.[Status] = 'Active'
AND UT.TaskStatus = 'Assigned'
AND T.Devices = 'No'
AND T.Title <> 'Applicability'
AND L.LegislationCategoryOID NOT IN(117, 118, 119, 120, 121, 122, 123, 124, 125)
AND T.CentralTaskOID NOT IN
(
SELECT CentralTaskOID
FROM GroupTask
)
AND U.EntityOID IN(27, 25, 26, 24)
AND u.UnitOID = UT.UnitOID
AND ((TL.ReviewerDt >= '12/17/2019'
AND TL.ReviewerDt <= '03/17/2020'
AND TL.PerformerDt <= '03/17/2020')
OR (TL.CompletedDt BETWEEN '12/17/2019' AND '03/17/2020')
OR (TL.ApproverDt >= '12/17/2019'
AND TL.ApproverDt <= '03/17/2020'))
UNION ALL
SELECT TL.DailyTaskOID AS OID,
E.EntityOID,
U.UnitOID,
D.DeptOID,
E.EntityName,
U.UnitName,
D.DeptName,
(CASE
WHEN ISNULL(LTRIM(RTRIM(U.ShortDesc)), '') = ''
THEN CONVERT(VARCHAR(50), UT.UnitTaskOID)
ELSE U.ShortDesc + '-' + CONVERT(VARCHAR(50), UT.UnitTaskOID)
END) AS 'UnitTaskWithDesc',
UT.[UnitTaskOID],
UT.[TaskOID],
T.LegislationOID,
T.CentralTaskOID,
L.LegislationCategoryOID,
C.LegislationCategory,
ISNULL(
(
SELECT C.CompanyCategory
FROM CompanyCategory C
WHERE C.CompanyCategoryOID = T.CompanyCategoryOID
), '-') CompanyCategory,
L.CentralState,
L.LegislationName,
T.Section_Rule_Regulation_Notification,
S.STATE_OID,
S.STATE_NAME,
T.[Title],
T.[PriorityOID],
P.Priority,
T.[FrequencyOID],
F.Frequency,
T.[Devices],
T.[Section_Rule_Regulation_Notification],
T.[Requirement_Apply],
T.[Task],
T.[Regulating_Authority],
T.[Consequences],
T.[Department],
TL.[Status] AS TaskStatus,
UT.PerformerUserOID,
D.DeptHeadOID,
ISNULL((UDFH.FIRST_NAME + ' ' + UDFH.LAST_NAME), '-') AS 'DeptHead',
UT.DeptSupervisorOID,
ISNULL((UDSup.FIRST_NAME + ' ' + UDSup.LAST_NAME), '-') AS 'Supervisor',
TL.PerformerUserOID AS 'PerformerUserOID_log',
ISNULL((UDPer.FIRST_NAME + ' ' + UDPer.LAST_NAME), '-') AS 'Performer',
ISNULL((UDComp.FIRST_NAME + ' ' + UDComp.LAST_NAME), '-') AS 'TaskCompletedBy',
dbo.FormatDate(#ClientCode, TL.ApproverDt) AS 'ApproverDt',
dbo.FormatDate(#ClientCode, TL.ReviewerDt) AS 'ReviewerDt',
dbo.FormatDate(#ClientCode, TL.SupervisorDt) AS 'SupervisorDt',
dbo.FormatDate(#ClientCode, TL.PerformerDt) AS 'PerformerDt',
CASE
WHEN #DeviationFunctionality = 'Yes'
THEN ISNULL(TL.Deviation, '-')
ELSE ''
END AS 'Deviation',
dbo.FormatDate(#ClientCode, TL.PerformedOnDt) AS 'PerformedOnDt',
dbo.FormatDate(#ClientCode, TL.CompletedDt) AS 'CompletedDt',
ISNULL(TL.Comments, '-') AS 'Comments',
('-') AS 'ActivationComment',
ISNULL(TL.ReasonForNonComp, '-') AS 'ReasonForNonComp',
ISNULL(TL.ActionTaken, '-') AS 'ActionTaken',
dbo.GetCompletionDate(#ClientCode, TL.CompletedDt, #ShowPerformedOnDate, #NoOfColorsInDashboardGraphs, TL.PerformedOnDt) AS 'Completed On',
dbo.GetCompletionComment('', TL.Comments, TL.ReviewerComment, TL.CompletedDt, TL.ReviewerCommentDate, TL.PeriodFromDate, TL.PeriodToDate) AS 'CompletionComments',
'' AS UnitDeviceOID,
'' AS TaskDeviceOID,
'' AS 'lblUnitDeviceOIDDesc',
dbo.GetComplianceStatus(TL.[Status], CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.ApproverDt, 112)), CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.CompletedDt, 112)), #NoOfColorsInDashboardGraphs, #TerminologyToNonCompliedCompletedTasks, #TerminologyToNonCompliedNonCompletedTasks, CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.PerformedOnDt, 112)), #ShowPerformedOnDate, #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt, #TerminologyToCompliedTasks, #TerminologyToPosingRiskTasks) AS 'ComplianceStatus',
ISNULL(TblLOGTMakerChecker.DailyTaskOID, 0) AS MKOID,
ISNULL(TCSV.TaskComplianceStatusValue, '-') AS TaskComplianceStatusValue,
ISNULL(TL.TaskComplianceStatusValueOID, 0) AS TaskComplianceStatusValueOID,
#NoOfColorsInDashboardGraphs AS 'NoOfColorsOnReport',
#TerminologyToNonCompliedCompletedTasks AS 'TerminologyToNonCompliedCompletedTask',
#TerminologyToNonCompliedNonCompletedTasks AS 'TerminologyToNonCompliedNonCompletedTask',
#ShowPerformedOnDate AS 'ShowPerformedOnDate',
#TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt AS 'TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt',
#TerminologyToCompliedTasks AS 'TerminologyToCompliedTasks',
(CASE
WHEN(
Yes, you cannot declare variables in a view.

How I can transform a stored procedure to a view?

I have this stored procedure which pulls data from 4 tables and ranks them by 4 columns, but I need a view with the same result (of course without parameter). Is this possible? I know that I can not use a temp table in view, any solution?!
ALTER PROC pr_GetChildrenByPersonID
#pePersonIDs varchar(8000)
AS
SELECT
*,
RANK() OVER (PARTITION BY pbsPersonID ORDER BY psbPersonSiblingID ASC) AS CustomRank
INTO
#TempPersonSibling
FROM
PersonSibling
WHERE
pbsSiblingTypeID = 2
AND pbsPersonID IN (SELECT item
FROM dbo.fn_ParseStrListIdentity(#pePersonIDs, ','))
SELECT
pePersonID,
ISNULL((SELECT pbsName
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 1), '') AS ChildrenName1,
ISNULL((SELECT pbsAge
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 1), '') AS ChildrenAge1,
ISNULL((SELECT dbo.fn_GetCountry(pbsPlaceOfBirth)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 1), '') AS ChildrenCountryOfBirth1,
ISNULL((SELECT dbo.fn_GetCountry(pbsPresentStay)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 1), '') AS ChildrenCountryOfResidence1,
ISNULL((SELECT pbsName
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 2), '') AS ChildrenName2,
ISNULL((SELECT pbsAge
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 2), '') AS ChildrenAge2,
ISNULL((SELECT dbo.fn_GetCountry(pbsPlaceOfBirth)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 2), '') AS ChildrenCountryOfBirth2,
ISNULL((SELECT dbo.fn_GetCountry(pbsPresentStay)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 2), '') AS ChildrenCountryOfResidence2,
ISNULL((SELECT pbsName
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 3), '') AS ChildrenName3,
ISNULL((SELECT pbsAge
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 3), '') AS ChildrenAge3,
ISNULL((SELECT dbo.fn_GetCountry(pbsPlaceOfBirth)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 3), '') AS ChildrenCountryOfBirth3,
ISNULL((SELECT dbo.fn_GetCountry(pbsPresentStay)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 3), '') AS ChildrenCountryOfResidence3,
ISNULL((SELECT pbsName
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 4), '') AS ChildrenName4,
ISNULL((SELECT pbsAge
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 4), '') AS ChildrenAge4,
ISNULL((SELECT dbo.fn_GetCountry(pbsPlaceOfBirth)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 4), '') AS ChildrenCountryOfBirth4,
ISNULL((SELECT dbo.fn_GetCountry(pbsPresentStay)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 4), '') AS ChildrenCountryOfResidence4
FROM
Person
WHERE
pePersonID IN (SELECT item
FROM dbo.fn_ParseStrListIdentity(#pePersonIDs, ','))
Use a Common Table Expression (CTE) instead of a temporary table, and use the CTE where you are using the temporary table now.
Like so:
WITH
TempPersonSibling AS (
-- the select statement that creates the temp table here
-- without the INTO clause
)
SELECT
pePersonID,
ISNULL((SELECT pbsName FROM TempPersonSibling WHERE pbsSiblingTypeID = 2 AND pbsPersonID = pepersonID AND CustomRank = 1),'') AS ChildrenName1,
-- ..., rest of the query is similar
FROM
Person
WHERE
-- ...
This way you can create a single query and package that in your view.

Error converting data type varchar to numeric for this below query

Error converting data type varchar to numeric for this below query
Please suggest what can i modify to fix
Update BUDTANKS
set BUDTANKS.SHELLCAPACITY = 0.0000000 --Numeric Column
,BUDTANKS.WORKINGCAPACITY = 0.0000000 --Numeric Column
,BUDTANKS.LEASEDCAPACITY = 0.0000000 --Numeric Column
,BUDTANKS.VERSIONID = 1
,BUDTANKS.STATUSID = 1
,BUDTANKS.IMPORTEDRECORD = 1
,BUDTANKS.LastModifiedUserID = 'Import'
,BUDTANKS.LASTMODIFIEDDATETIME = GETDATE()
FROM BUDTANKS BTANK WITH(NOLOCK)
INNER JOIN BUDTERMINALS BT WITH(NOLOCK) ON BT.TERMINALID = BTANK.TERMINALID
INNER JOIN External_Liq_Itm_Tanks ELIT WITH(NOLOCK) ON ELIT.TerminalName = BT.MBFTERMINALNAME AND ELIT.TankName = BTANK.TANKNAME
Where (ISNULL(BTANK.SHELLCAPACITY, '') <> ISNULL(0.0000000, '')
OR ISNULL(BTANK.WORKINGCAPACITY, '') <> ISNULL(0.0000000, '')
OR ISNULL(BTANK.LEASEDCAPACITY, '') <> ISNULL(0.0000000, '')
OR (BTANK.STATUSID <> 1)
OR (BTANK.IMPORTEDRECORD <> 1))
I think your problem with this query is in the Where condition:
Where (ISNULL(BTANK.SHELLCAPACITY, '') <> ISNULL(0.0000000, '')
OR ISNULL(BTANK.WORKINGCAPACITY, '') <> ISNULL(0.0000000, '')
OR ISNULL(BTANK.LEASEDCAPACITY, '') <> ISNULL(0.0000000, '')
OR (BTANK.STATUSID <> 1)
OR (BTANK.IMPORTEDRECORD <> 1))
You need to change it to:
Where (ISNULL(BTANK.SHELLCAPACITY, 0) <> 0)
OR ISNULL(BTANK.WORKINGCAPACITY,0) <> 0)
OR ISNULL(BTANK.LEASEDCAPACITY, 0) <> 0)
OR (BTANK.STATUSID <> 1)
OR (BTANK.IMPORTEDRECORD <> 1))
or
Where BTANK.SHELLCAPACITY Is Not Null
OR BTANK.WORKINGCAPACITY Is Not Null
OR BTANK.LEASEDCAPACITY Is Not Null
OR (BTANK.STATUSID <> 1)
OR (BTANK.IMPORTEDRECORD <> 1))

My query takes a long time

Here is my code:
SELECT SpecieCode AS [Species]
,InventoryGrade AS [Grade]
,(
SELECT Sum(SquareFeet)
FROM Export AS Export1
WHERE isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(OrderNumber, '') = ''
AND isnull(InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(ShowNumber, '') = ''
) AS [SqFt Avail]
,(
SELECT Sum(SquareMeters)
FROM Export AS Export1
WHERE isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(OrderNumber, '') = ''
AND isnull(InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(ShowNumber, '') = ''
) AS [SqMt Avail]
,(
SELECT Sum(SquareFeet)
FROM Export AS Export1
WHERE isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(InvoiceNumber, '') = ''
AND isnull(OrderNumber, '') > ''
) AS [SqFt on Order]
,(
SELECT Sum(SquareMeters)
FROM Export AS Export1
WHERE isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(OrderNumber, '') > ''
) AS [SqMt on Order]
,(
SELECT Sum(SquareFeet)
FROM Export AS Export1
WHERE isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(InvoiceNumber, '') = ''
AND isnull(OrderNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(ShowNumber, '') > ''
) AS [SqFt on Show]
,(
SELECT Sum(SquareMeters)
FROM Export AS Export1
WHERE isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(InvoiceNumber, '') = ''
AND isnull(Ordernumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(ShowNumber, '') > ''
) AS [SqMt on Show]
,(
SELECT Sum(SquareMeters)
FROM Export AS Export1
WHERE isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(Export1.InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
) AS [Tot SqMt]
,Max(SubGrade) AS SubGrade
,Min(ShortLength) AS Short
,Max(Length) AS Long
,Max(InventoryRow) AS Location
FROM Export
WHERE Export.SpecieCode = '01'
AND isnull(Export.InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
GROUP BY SpecieCode
,InventoryGrade
ORDER BY SpecieCode
,InventoryGrade
The query currently takes several minutes to run. Is there anything I can do to speed it up? The Analyzer is not suggesting to add any indexes.
In addition to the answers given by Simo and Benjamin, you should check out this question about sargable queries. In short, by saying something like where IsNull(MyColumn,'') = '' you are killing the query analyzer's ability to find a good index, if one exists, since there can be no index on IsNull(MyColumn,''). If you were to rewrite that as where (MyColumn is null or MyColumn = '') then you will probably get better performance, since the query analyzer will be more likely to find a good index.
You have multiple subqueries in the SELECT list and many of these are not necessary. You could at least try to optimize the query a little with CASE clauses. Note: you have to verify the results and possibly use only parts of this query depending on you data.
SELECT Export.SpecieCode AS [Species]
,Export.InventoryGrade AS [Grade]
,sum(CASE WHEN
isnull(OrderNumber, '') = ''
AND isnull(InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(ShowNumber, '') = ''
THEN Export1.SquareFeet ELSE 0 END) AS [SqFt Avail]
,sum(CASE WHEN
isnull(OrderNumber, '') = ''
AND isnull(InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(ShowNumber, '') = ''
THEN Export1.SquareMeters ELSE 0 END) AS [SqMt Avail]
,sum (CASE WHEN
isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(InvoiceNumber, '') = ''
AND isnull(OrderNumber, '') > ''
THEN Export1.SquareFeet ELSE 0 END) AS [SqFt on Order]
,sum (CASE WHEN
isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(OrderNumber, '') > ''
THEN Export1.SquareMeters ELSE 0 END) AS [SqMt on Order]
,sum(CASE WHEN
isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(InvoiceNumber, '') = ''
AND isnull(OrderNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(ShowNumber, '') > ''
THEN Export1.SquareFeet ELSE 0 END) AS [SqFt on Show]
,sum(CASE WHEN
isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(InvoiceNumber, '') = ''
AND isnull(Ordernumber, '') = ''
AND isnull(FaceClipDate, '') = ''
AND isnull(ShowNumber, '') > ''
THEN Export1.SquareMeters ELSE 0 END) AS [SqMt on Show]
,sum(CASE WHEN
isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
AND isnull(Export1.InvoiceNumber, '') = ''
AND isnull(FaceClipDate, '') = ''
THEN Export1.SquareMeters ELSE 0 END) AS [Tot SqMt]
,Max(Export.SubGrade) AS SubGrade
,Min(Export.ShortLength) AS Short
,Max(Export.Length) AS Long
,Max(Export.InventoryRow) AS Location
FROM Export
JOIN Export AS Export1 ON isnull(Export1.SpecieCode, '') = isnull(Export.SpecieCode, '')
AND isnull(Export1.InventoryGrade, '') = isnull(Export.InventoryGrade, '')
WHERE Export.SpecieCode = '01'
Your results were probably incorrect because of nulls appearing in one of the columns so you may have gone overboard by wrapping every column with an isnull. In my experience only certain columns are likely to contain nulls or will mess up your results by containing nulls. Otherwise (leaving in all the isnulls) the query will take time.
You probably should use if var1 is null instead of isnull(something,'')=''
when I tried this:
declare #i1 int=0
declare #a2 varchar(20)
set #a2 = null
begin
if ISNULL(#a2,'')='' set #i1 +=1
end
go 1000
vs
declare #i1 int=0
declare #a2 varchar(20)
set #a2 = null
begin
if #a2 is null set #i1 +=1
end
go 1000
The second test took 18 seconds vs 35 seconds for the first type of compare.

sql server query concat string with '-'

In my SQL query, I'm trying to concatenate two strings in my select clause. Here's the expected results:
col A col B Result
null null &
null '' &
null XYZ XYC
'' null &
'' '' &
'' XYZ XYC
ABC null ABC
ABC '' ABC
ABC XYZ ABC-XYC
My challenge is this - how do I get the 'dash' to show up for the last scenario and not the others?
Here's my attempt:
DECLARE #ColA as varchar(10)
DECLARE #ColB as varchar(10)
set #ColA = null; set #ColB = null; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = null; set #ColB = ''; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = null; set #ColB = 'XYC'; select 'XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = null; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = ''; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = 'XYC'; select 'XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = null; select 'ABC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = ''; select 'ABC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = 'XYC'; select 'ABC-XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
Do you think I have to do one giant case when? I have many columns like this, and that would make it unbearable to read.
Thanks!
UPDATE: if I use a case when, then my select looks like this, which seems to work, but is going to be a pain.
select
case when (#ColA is not null and #ColA <> '') and
(#ColB is not null and #ColB <> '')
then #ColA + '-' + #ColB
else COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&')
end
really hoping someone has some suggestions for improvement!
Could you use a searched case function like this?
Select Case When isnull(ColA, '') + isnull(ColB, '') == '' Then '&'
When isnull(ColA, '') <> '' and isnull(ColB, '') <> '' Then ColA + '-' + ColB
Else isnull(ColA, '') + isnull(ColB, '')
From Table1
I think this answer isn't a whole lot different than one of the other ones, but you might try this:
SELECT
CASE
WHEN NULLIF(ColA,'') <> '' AND NULLIF(ColB,'') <> ''
THEN ColA + '-' + ColB
WHEN NULLIF(ColA,'') <> '' OR NULLIF(ColB,'') <> ''
THEN COALESCE(ColA,ColB)
ELSE '&'
END

Resources