Related
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.
Is there particular syntax for writing nested case statement?
I have a stored procedure that I need to figure out what is going on and thought maybe there is an easier way to understand nested case statement?
SELECT
CASE
WHEN ISNULL(NetRate_Quote_Insur_Quote_Locat.[Transaction], '') <> '' AND NetRate_Quote_Insur_Quote_Locat.EndorsementNumber = NetRate_Quote_Insur_Quote.EndorsementNumber
THEN
CASE
NetRate_Quote_Insur_Quote_Locat.[Transaction]
WHEN 'ADD' THEN 'Add'
WHEN 'DELETED' THEN 'Delete'
WHEN 'CHANGED' THEN 'Change'
WHEN 'New Quote' THEN 'Add'
ELSE
CASE
WHEN tblQuotes.OriginalQuoteGuid IS NULL OR NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate'
THEN 'Add'
ELSE
CASE WHEN tblQuotes.QuoteStatusID = 12
THEN 'Delete'
ELSE 'No Change'
END
END
END
ELSE
CASE WHEN tblQuotes.OriginalQuoteGuid IS NULL OR NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate'
THEN 'Add'
ELSE
CASE
WHEN tblQuotes.QuoteStatusID = 12
THEN 'Delete'
ELSE 'No Change'
END
END
END as TransactionName
FROM
Personally, I'd write it like this:
select
case
when isNull(NetRate_Quote_Insur_Quote_Locat.[Transaction], '') <> ''
and NetRate_Quote_Insur_Quote_Locat.EndorsementNumber
= NetRate_Quote_Insur_Quote.EndorsementNumber
then
case NetRate_Quote_Insur_Quote_Locat.[Transaction]
when 'ADD' then 'Add'
when 'DELETED' then 'Delete'
when 'CHANGED' then 'Change'
when 'New Quote' then 'Add'
else
case
when tblQuotes.OriginalQuoteGuid is null
or NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate'
then 'Add'
else
case
when tblQuotes.QuoteStatusID = 12
then 'Delete'
else 'No Change'
end
end
end
else
case
when tblQuotes.OriginalQuoteGuid is null
or NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate'
then 'Add'
else
case
when tblQuotes.QuoteStatusID = 12
then 'Delete'
else 'No Change'
end
end
end as TransactionName
from ...
But I'd remove some case's:
select
case
when isNull(NetRate_Quote_Insur_Quote_Locat.[Transaction], '')
in ('ADD','DELETE','CHANGED','New Quote')
and NetRate_Quote_Insur_Quote_Locat.EndorsementNumber
= NetRate_Quote_Insur_Quote.EndorsementNumber
then
case NetRate_Quote_Insur_Quote_Locat.[Transaction]
when 'ADD' then 'Add'
when 'DELETED' then 'Delete'
when 'CHANGED' then 'Change'
when 'New Quote' then 'Add'
end
else
case
when tblQuotes.OriginalQuoteGuid is null
or NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate'
then 'Add'
else
case
when tblQuotes.QuoteStatusID = 12
then 'Delete'
else 'No Change'
end
end
end as TransactionName
from ...
This variation flattens the CASE WHEN tblQuotes.QuoteStatusID = 12 logic into the surrounding case for both occurrences since there is no benefit in nesting the searched case expressions:
case
when IsNull( NetRate_Quote_Insur_Quote_Locat.[Transaction], '' ) <> '' and
NetRate_Quote_Insur_Quote_Locat.EndorsementNumber = NetRate_Quote_Insur_Quote.EndorsementNumber
then
case NetRate_Quote_Insur_Quote_Locat.[Transaction]
when 'ADD' then 'Add'
when 'DELETED' then 'Delete'
when 'CHANGED' then 'Change'
when 'New Quote' then 'Add'
else
case
when tblQuotes.OriginalQuoteGuid is NULL or NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate'
then 'Add'
when tblQuotes.QuoteStatusID = 12 then 'Delete'
else 'No Change'
end
end
else
case
when tblQuotes.OriginalQuoteGuid is NULL or NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate'
then 'Add'
when tblQuotes.QuoteStatusID = 12 then 'Delete'
else 'No Change'
end
end as TransactionName
If NetRate_Quote_Insur_Quote_Locat.[Transaction] can only have the values listed ('ADD', 'DELETED', 'CHANGED' and 'New Quote') then any other value would result in a NULL result in the absence of an else clause. You can use that with coalesce to collapse the large block of repeating code:
Coalesce(
case
when IsNull( NetRate_Quote_Insur_Quote_Locat.[Transaction], '' ) <> '' and
NetRate_Quote_Insur_Quote_Locat.EndorsementNumber = NetRate_Quote_Insur_Quote.EndorsementNumber
then
case NetRate_Quote_Insur_Quote_Locat.[Transaction]
when 'ADD' then 'Add'
when 'DELETED' then 'Delete'
when 'CHANGED' then 'Change'
when 'New Quote' then 'Add'
end,
case
when tblQuotes.OriginalQuoteGuid is NULL or NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate'
then 'Add'
when tblQuotes.QuoteStatusID = 12 then 'Delete'
else 'No Change'
end ) as TransactionName
When table or column names make things get very horizontal, I use aliases. So in your 'from' and 'join' statements, I would alias NetRate_Quote_insur_quote to something like 'nQuote', and 'NetRate_Quote_insur_quote_locat' to something like 'loc'.
Besides that, for things that take more than one line, I like the colName = xyz syntax.
Also I like 'case' lined up with the 'when', 'else', and 'end' statements, and if feasible, 'then' statements not in line with these rest.
So it would look like this:
select TransactionName =
CASE
WHEN ISNULL(loc.[Transaction], '') <> '' AND loc.EndorsementNumber = nQuote.EndorsementNumber THEN
CASE loc.[Transaction]
WHEN 'ADD' THEN 'Add'
WHEN 'DELETED' THEN 'Delete'
WHEN 'CHANGED' THEN 'Change'
WHEN 'New Quote' THEN 'Add'
ELSE
CASE
WHEN tblQuotes.OriginalQuoteGuid IS NULL OR nQuote.TypeofBusiness = 'Reinstate' THEN 'Add'
ELSE
CASE WHEN tblQuotes.QuoteStatusID = 12 THEN 'Delete'
ELSE 'No Change'
END
END
END
ELSE
CASE
WHEN tblQuotes.OriginalQuoteGuid IS NULL OR nQuote.TypeofBusiness = 'Reinstate' THEN 'Add'
ELSE
CASE
WHEN tblQuotes.QuoteStatusID = 12 THEN 'Delete'
ELSE 'No Change'
END
END
END
Also, I find often it is helpful to put repeating case logic into cross apply statements. So if, after your join statements, you can add something like:
cross apply (select
endorsed =
case
when ISNULL(loc.[Transaction], '') <> '' AND loc.EndorsementNumber = nQuote.EndorsementNumber then 1
else 0
end,
nullOrReinstate =
case
when tblQuotes.OriginalQuoteGuid IS NULL OR nQuote.TypeofBusiness = 'Reinstate' then 1
else 0
end
) ap
then you can use those columns in your logic. In the end, if I didn't make a mistake, I believe your case statement can be unnested to look like this:
select TransactionName =
CASE
WHEN endorsed = 1 and loc.[Transaction] in ('add', 'deleted', 'changed') then loc.[transaction]
WHEN endorsed = 1 and loc.[transaction] = 'New Quote' THEN 'Add'
WHEN endorsed = 1 and nullOrReinstate = 1 THEN 'Add'
WHEN endorsed = 1 and tblQuotes.QuoteStatusID = 12 THEN 'Delete'
WHEN nullOrReinstate = 1 THEN 'Add'
WHEN tblQuotes.QuoteStatusID = 12 THEN 'Delete'
ELSE 'No Change'
END
I'm pretty sure that most of this is unnecessary. I resolved it out and think that the outer case is not required because you are checking for transaction being not empty, then in a nested check testing for its values. If you exclude this part then the two outer case conditions are the same, which means the whole nesting can be removed. I'm pretty sure it evaluates to the below.
In general you have a lot of ELSE CASE xxx clauses where the second case could simply be added as more WHEN clauses to the original case, particularly if you dont use the CASE value and replace it with the CASE WHEN value= syntax.
This is what I think it all resolves to:
CASE
WHEN NetRate_Quote_Insur_Quote_Locat.[Transaction]='ADD' THEN 'Add'
WHEN NetRate_Quote_Insur_Quote_Locat.[Transaction]='DELETED' THEN 'Delete'
WHEN NetRate_Quote_Insur_Quote_Locat.[Transaction]='CHANGED' THEN 'Change'
WHEN NetRate_Quote_Insur_Quote_Locat.[Transaction]='New Quote' THEN 'Add'
WHEN tblQuotes.OriginalQuoteGuid IS NULL OR NetRate_Quote_Insur_Quote.TypeofBusiness = 'Reinstate' THEN 'Add'
WHEN tblQuotes.QuoteStatusID = 12 THEN 'Delete'
ELSE 'No Change'
END as TransactionName
I can save you few lines
case NetRate_Quote_Insur_Quote_Locat.[Transaction]
when 'ADD' then 'Add'
when 'DELETED' then 'Delete'
when 'CHANGED' then 'Change'
Can become
case when NetRate_Quote_Insur_Quote_Locat.[Transaction] in ('ADD', 'DELETED', 'CHANGED') then LEFT(NetRate_Quote_Insur_Quote_Locat.[Transaction], 6)
So I have created a view, but I seem to be getting an error I do not seem to understand why, I am just assigning the value, I am posting the code here
SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN commodityid = 1 THEN 0 ELSE 1 END) AS ID,
CommodityID,
CommodityName,
SubCommodityID,
SubCommodityName,
SectorID,
Sector,
GroupID,
GroupName,
StatisticID,
StatisticType,
SourceID,
Source,
SourceDescription,
PhysicalAttributeID,
PhysicalAttribute,
UtilizationID,
UtilizationPractice,
ProductionPracticeID,
ProductionPractice,
Description,
SourceSeriesID,
TimeID,
TimeFrequency,
Date,
GeographyID,
GeographyType,
City,
County,
State,
Region,
Country,
UnitID,
Unit,
LifecyclePhaseID,
LifecyclePhaseDescription AS Value
FROM (SELECT DISTINCT
dv.ERSDataValues_ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
cds.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
su.ERSSector_ID AS SectorID,
su.ERSSector_Desc AS Sector,
gu.ERSGroup_ID AS GroupID,
gu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
phlu.ERSPhysicalAttribute_ID AS PhysicalAttributeID,
cds.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
upu.ERSUtilPractice_ID AS UtilizationID,
upu.ERSUtilPractice_Desc AS UtilizationPractice,
pu.ERSProdPractice_ID AS ProductionPracticeID,
pu.ERSProdPractice_Desc AS ProductionPractice,
CASE
WHEN cds.ERSCommodity_SourceSeriesID_LongDesc IS NULL THEN 'No Description'
ELSE cds.ERSCommodity_SourceSeriesID_LongDesc
END AS Description,
CASE
WHEN cds.ERSCommodity_SourceSeriesID IS NULL THEN 'No SourceSeriesID'
ELSE cds.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdt.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tu.ERSTimeDimension_Date AS Date,
gdu.ERSGeographyDimension_ID AS GeographyID,
gtu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
dv.ERSDataValues_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
dv.ERSDataValues_AttributeValue AS Value
FROM CoSD.ERSCommodityDataSeries cds
INNER JOIN cosd.ERSPhysicalAttribute_LU phlu ON phlu.ERSPhysicalAttribute_ID = cds.ERSCommodity_ERSPhysicalAttribute_ID
INNER JOIN CoSD.ERSDataValues dv ON cds.ERSCommodity_ID = dv.ERSDataValues_ERSCommodity_ID
INNER JOIN CoSD.ERSSector_LU su ON cds.ERSCommodity_ERSSector_ID = su.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU gu ON cds.ERSCommodity_ERSGroup_ID = gu.ERSGroup_ID
INNER JOIN CoSD.ERSProdPractice_LU pu ON cds.ERSCommodity_ERSProdPractice_ID = pu.ERSProdPractice_ID
INNER JOIN CoSD.ERSUtilPractice_LU upu ON cds.ERSCommodity_ERSUtilPractice_ID = upu.ERSUtilPractice_ID
AND cds.ERSCommodity_ERSUtilPractice_ID = upu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSUnit_LU ulu ON dv.ERSDataValues_ERSUnit_ID = ulu.ERSUnit_ID
INNER JOIN CoSD.ERSSource_LU slu ON cds.ERSCommodity_ERSSource_ID = slu.ERSSource_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON cds.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSTimeDimension_LU tu ON dv.ERSDataValues_ERSTimeDimension_ID = tu.ERSTimeDimension_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdu ON dv.ERSDataValues_ERSGeography_ID = gdu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSTimeDimensionType_LU tdt ON tu.ERSTimeDimension_TimeDimensionType_ID = tdt.ERSTimeDimensionType_ID
INNER JOIN CoSD.ERSGeographyType_LU gtu ON gdu.ERSGeographyDimension_ERSGeographyType_ID = gtu.ERSGeographyType_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON csc.ERSCommoditySubCommodity_ID = cds.ERSCommoditySubCommodity_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = dv.ERSDataValues_DataRowLifecyclePhaseID
WHERE dv.ERSDataRowPrivacy_ID = 1
AND dv.ERSDataValues_AttributeValue IS NOT NULL
UNION ALL
SELECT DISTINCT
cds.ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
csc.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
slu.ERSSector_ID AS SectorID,
slu.ERSSector_Desc AS Sector,
glu.ERSGroup_ID AS GroupID,
glu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
selu.ERSSource_ID AS SourceID,
cvo.ERSConstructedVariable_InputSources AS Source,
selu.ERSSource_LongDesc AS SourceDescription,
cds.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID,
cds.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
ulu.ERSUtilPractice_ID AS UtilizationID,
ulu.ERSUtilPractice_Desc AS UtilizationPractice,
plu.ERSProdPractice_ID AS ProductionPracticeID,
plu.ERSProdPractice_Desc AS ProductionPractice,
cvo.ERSConstructedVariable_OutputName AS Description,
CASE
WHEN cds.ERSCommodity_SourceSeriesID LIKE '%(N%' THEN 'No SourceSeriesID'
ELSE cds.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
cvo.ERSConstructedVariable_TimeDimensionDate AS Date,
gdlu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdlu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdlu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdlu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdlu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdlu.ERSGeographyDimension_Country
END AS Country,
unlu.ERSUnit_ID AS UnitID,
unlu.ERSUnit_Desc AS Unit,
cvo.ERSConstructedVariable_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
cvo.ERSConstructedVariable_OutputValue AS Value
FROM CoSD.ERSConstructedVariablesOutcomes cvo
INNER JOIN CoSD.ERSCommodityDataSeries cds ON cvo.ERSConstructedVariable_NewDataSeriesID = cds.ERSCommodity_ID
INNER JOIN CoSD.ERSSector_LU slu ON cds.ERSCommodity_ERSSector_ID = slu.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU glu ON cds.ERSCommodity_ERSGroup_ID = glu.ERSGroup_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON cds.ERSCommoditySubCommodity_ID = csc.ERSCommoditySubCommodity_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON cds.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSUtilPractice_LU ulu ON cds.ERSCommodity_ERSUtilPractice_ID = ulu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSProdPractice_LU plu ON cds.ERSCommodity_ERSProdPractice_ID = plu.ERSProdPractice_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdlu ON cvo.ERSConstructedVariable_OutputGeographyDimensionID = gdlu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSUnit_LU unlu ON cvo.ERSConstructedVariable_OutputUnitID = unlu.ERSUnit_ID
INNER JOIN CoSD.ERSGeographyType_LU gtlu ON gdlu.ERSGeographyDimension_ERSGeographyType_ID = gtlu.ERSGeographyType_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = cvo.ERSConstructedVariable_TimeDimensionID
AND tlu.ERSTimeDimension_Date = cvo.ERSConstructedVariable_TimeDimensionDate
AND YEAR(tlu.ERSTimeDimension_Date) = YEAR(cvo.ERSConstructedVariable_TimeDimensionDate)
AND MONTH(tlu.ERSTimeDimension_Date) = MONTH(ERSConstructedVariable_TimeDimensionDate)
INNER JOIN cosd.ERSTimeDimensionType_LU tdlu ON tdlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSSource_LU selu ON cvo.ERSConstructedVariable_InputSourceID = selu.ERSSource_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = cvo.ERSConstructedVariable_DataRowLifecyclePhaseID
WHERE cvo.ERSConstructedVariable_DataRowPrivacyID = 1
AND cvo.ERSConstructedVariable_NewDataSeriesID IS NOT NULL
AND cvo.ERSConstructedVariable_OutputValue IS NOT NULL
UNION ALL
SELECT DISTINCT
CDS.ERSCommodity_ID AS CommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN SUBSTRING(csc.ERSCommoditySubCommodity_Desc, 1, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) - 1)
ELSE csc.ERSCommoditySubCommodity_Desc
END AS CommodityName,
csc.ERSCommoditySubCommodity_ID AS SubCommodityID,
CASE
WHEN CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) > 0 THEN LTRIM(SUBSTRING(csc.ERSCommoditySubCommodity_Desc, CHARINDEX(',', csc.ERSCommoditySubCommodity_Desc) + 1, LEN(csc.ERSCommoditySubCommodity_Desc)))
ELSE 'No SubCommodity'
END AS SubCommodityName,
slu.ERSSector_ID AS SectorID,
slu.ERSSector_Desc AS Sector,
glu.ERSGroup_ID AS GroupID,
glu.ERSGroup_Desc AS GroupName,
stu.ERSStatisticType_ID AS StatisticID,
stu.ERSStatisticType_Attribute AS StatisticType,
selu.ERSSource_ID AS SourceID,
cvo.ERSConstructedVariable_InputSources AS Source,
selu.ERSSource_LongDesc AS SourceDescription,
CDS.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID,
CDS.ERSCommodity_PhysicalAttribute_Desc AS PhysicalAttribute,
ulu.ERSUtilPractice_ID AS UtilizationID,
ulu.ERSUtilPractice_Desc AS UtilizationPractice,
plu.ERSProdPractice_ID AS ProductionPracticeID,
plu.ERSProdPractice_Desc AS ProductionPractice,
cvo.ERSConstructedVariable_OutputName AS Description,
CASE
WHEN CDS.ERSCommodity_SourceSeriesID IS NULL THEN 'No SourceSeriesID'
ELSE CDS.ERSCommodity_SourceSeriesID
END AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(tdlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
cvo.ERSConstructedVariable_TimeDimensionDate AS Date,
gdlu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE gdlu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE gdlu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE gdlu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE gdlu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(gdlu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE gdlu.ERSGeographyDimension_Country
END AS Country,
unlu.ERSUnit_ID AS UnitID,
unlu.ERSUnit_Desc AS Unit,
cvo.ERSConstructedVariable_DataRowLifecyclePhaseID AS LifecyclePhaseID,
dlu.ERSDataLifecyclePhase_Desc AS LifecyclePhaseDescription,
cvo.ERSConstructedVariable_OutputValue AS Value
FROM CoSD.ERSConstructedVariablesOutcomes cvo
INNER JOIN CoSD.ERSBusinessLogic BL ON cvo.ERSConstructedVariable_BusinessLogicID = BL.ERSBusinessLogic_ID
INNER JOIN cosd.ERSCommodityDataSeries CDS ON CDS.ERSCommodity_ID = BL.ERSBusinessLogic_InputDataSeries
INNER JOIN CoSD.ERSSector_LU slu ON CDS.ERSCommodity_ERSSector_ID = slu.ERSSector_ID
INNER JOIN CoSD.ERSGroup_LU glu ON CDS.ERSCommodity_ERSGroup_ID = glu.ERSGroup_ID
INNER JOIN CoSD.ERSCommoditySubCommodity_LU csc ON CDS.ERSCommoditySubCommodity_ID = csc.ERSCommoditySubCommodity_ID
INNER JOIN CoSD.ERSStatisticType_LU stu ON CDS.ERSCommodity_ERSStatisticType_ID = stu.ERSStatisticType_ID
INNER JOIN CoSD.ERSUtilPractice_LU ulu ON CDS.ERSCommodity_ERSUtilPractice_ID = ulu.ERSUtilPractice_ID
INNER JOIN CoSD.ERSProdPractice_LU plu ON CDS.ERSCommodity_ERSProdPractice_ID = plu.ERSProdPractice_ID
INNER JOIN CoSD.ERSGeographyDimension_LU gdlu ON cvo.ERSConstructedVariable_OutputGeographyDimensionID = gdlu.ERSGeographyDimension_ID
INNER JOIN CoSD.ERSUnit_LU unlu ON cvo.ERSConstructedVariable_OutputUnitID = unlu.ERSUnit_ID
INNER JOIN CoSD.ERSGeographyType_LU gtlu ON gdlu.ERSGeographyDimension_ERSGeographyType_ID = gtlu.ERSGeographyType_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = cvo.ERSConstructedVariable_TimeDimensionID
AND tlu.ERSTimeDimension_Date = cvo.ERSConstructedVariable_TimeDimensionDate
AND YEAR(tlu.ERSTimeDimension_Date) = YEAR(cvo.ERSConstructedVariable_TimeDimensionDate)
AND MONTH(tlu.ERSTimeDimension_Date) = MONTH(ERSConstructedVariable_TimeDimensionDate)
INNER JOIN cosd.ERSTimeDimensionType_LU tdlu ON tdlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSSource_LU selu ON cvo.ERSConstructedVariable_InputSourceID = selu.ERSSource_ID
INNER JOIN cosd.ERSDataLifecycle_LU dlu ON dlu.ERSDataLifecyclePhase_ID = cvo.ERSConstructedVariable_DataRowLifecyclePhaseID
WHERE cvo.ERSConstructedVariable_DataRowPrivacyID = 1
AND BL.ERSBusinessLogic_InputsCount = 1
AND BL.ERSBusinessLogic_InputDataSeries NOT LIKE '%CV%'
AND cvo.ERSConstructedVariable_NewDataSeriesID IS NULL
AND cvo.ERSConstructedVariable_OutputValue IS NOT NULL
UNION ALL
SELECT DISTINCT
'-1' AS CommodityID,
ERSMacro_Desc AS CommodityName,
'-1' AS SubCommodityID,
ERSMacro_LongDesc AS SubCommodityName,
'4' AS SectorID,
'Macro' AS Sector,
'17' AS GroupID,
'Macro' AS GroupName,
NULL AS StatisticID,
'No StatisticType' AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
TRY_CONVERT(varchar, 'No PhysicalAttributeID') AS PhysicalAttributeID,
'No PhysicalAttribute' AS PhysicalAttribute,
'No UtilizationID' AS UtilizationID,
'No UtilizationPractice' AS UtilizationPractice,
'No ProductionPracticeID' AS ProductionPracticeID,
'No ProductionPractice' AS ProductionPractice,
'No Description' AS Description,
'No SourceSeriesID' AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(ttlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tlu.ERSTimeDimension_Date AS Date,
glu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE glu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE glu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE glu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE glu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE glu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
'No LifecyclephaseID' AS LifecyclePhaseID,
'No LifecyclePhaseDescription' AS LifecyclePhaseDescription,
mlu.ERSMacro_Value AS Value
FROM cosd.ERSMacro_LU mlu
INNER JOIN cosd.ERSSource_LU slu ON slu.ERSSource_ID = mlu.ERSMacro_Source_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = mlu.ERSMacro_TimeDimension_ID
INNER JOIN cosd.ERSTimeDimensionType_LU ttlu ON ttlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSGeographyDimension_LU glu ON glu.ERSGeographyDimension_ID = mlu.ERSMacro_GeographyDimension_ID
INNER JOIN cosd.ERSGeographyType_LU gtlu ON gtlu.ERSGeographyType_ID = glu.ERSGeographyDimension_ERSGeographyType_ID
INNER JOIN cosd.ERSUnit_LU ulu ON ulu.ERSUnit_ID = mlu.ERSMacro_Unit_ID) derived;
I get this error :
Conversion failed when converting the varchar value 'No PhysicalAttributeID' to data type int.
But the best part is if I run the last part of the code as below
SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN CommodityID = 1 THEN 0 ELSE 1 END) AS ID,
CommodityID,
CommodityName,
SubCommodityID,
SubCommodityName,
SectorID,
Sector,
GroupID,
GroupName,
StatisticID,
StatisticType,
SourceID,
Source,
SourceDescription,
PhysicalAttributeID,
PhysicalAttribute,
UtilizationID,
UtilizationPractice,
ProductionPracticeID,
ProductionPractice,
Description,
SourceSeriesID,
TimeID,
TimeFrequency,
Date,
GeographyID,
GeographyType,
City,
County,
State,
Region,
Country,
UnitID,
Unit,
LifecyclePhaseID,
LifecyclePhaseDescription,
Value
FROM (SELECT DISTINCT
'-1' AS CommodityID,
ERSMacro_Desc AS CommodityName,
'-1' AS SubCommodityID,
ERSMacro_LongDesc AS SubCommodityName,
'4' AS SectorID,
'Macro' AS Sector,
'17' AS GroupID,
'Macro' AS GroupName,
'No Statistic' AS StatisticID,
'No StatisticType' AS StatisticType,
slu.ERSSource_ID AS SourceID,
slu.ERSSource_Desc AS Source,
slu.ERSSource_LongDesc AS SourceDescription,
'No PhysicalAttributeID' AS PhysicalAttributeID,
'No PhysicalAttribute' AS PhysicalAttribute,
'No UtilizationID' AS UtilizationID,
'No UtilizationPractice' AS UtilizationPractice,
'No ProductionPracticeID' AS ProductionPracticeID,
'No ProductionPractice' AS ProductionPractice,
'No Description' AS Description,
'No SourceSeriesID' AS SourceSeriesID,
tlu.ERSTimeDimension_ID AS TimeID,
REPLACE(ttlu.ERSTimeDimensionType_Desc, 'ERS', '') AS TimeFrequency,
tlu.ERSTimeDimension_Date AS Date,
glu.ERSGeographyDimension_ID AS GeographyID,
gtlu.ERSGeographyType_Desc AS GeographyType,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_City, '') = '' THEN 'No City'
ELSE glu.ERSGeographyDimension_City
END AS City,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_County, '') = '' THEN 'No County'
ELSE glu.ERSGeographyDimension_County
END AS County,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_State, '') = '' THEN 'No State'
ELSE glu.ERSGeographyDimension_State
END AS State,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Region, '') = '' THEN 'No Region'
ELSE glu.ERSGeographyDimension_Region
END AS Region,
CASE
WHEN COALESCE(glu.ERSGeographyDimension_Country, '') = '' THEN 'No Country'
ELSE glu.ERSGeographyDimension_Country
END AS Country,
ulu.ERSUnit_ID AS UnitID,
ulu.ERSUnit_Desc AS Unit,
'No LifecyclephaseID' AS LifecyclePhaseID,
'No LifecyclePhaseDescription' AS LifecyclePhaseDescription,
mlu.ERSMacro_Value AS Value
FROM cosd.ERSMacro_LU mlu
INNER JOIN cosd.ERSSource_LU slu ON slu.ERSSource_ID = mlu.ERSMacro_Source_ID
INNER JOIN cosd.ERSTimeDimension_LU tlu ON tlu.ERSTimeDimension_ID = mlu.ERSMacro_TimeDimension_ID
INNER JOIN cosd.ERSTimeDimensionType_LU ttlu ON ttlu.ERSTimeDimensionType_ID = tlu.ERSTimeDimension_TimeDimensionType_ID
INNER JOIN cosd.ERSGeographyDimension_LU glu ON glu.ERSGeographyDimension_ID = mlu.ERSMacro_GeographyDimension_ID
INNER JOIN cosd.ERSGeographyType_LU gtlu ON gtlu.ERSGeographyType_ID = glu.ERSGeographyDimension_ERSGeographyType_ID
INNER JOIN cosd.ERSUnit_LU ulu ON ulu.ERSUnit_ID = mlu.ERSMacro_Unit_ID) derived;
This runs perfectly without any problems. If I change 'No PhysicalAttributeID' to null, it runs properly, I have tried this solution and also this
I seem to be heading no where, any ideas ?
It is because in the first query column 15 is PhysicalAttributeID which is almost certainly an int. Then you attempt to use UNION ALL to your second query. It will attempt an implicit conversion and fail.
An easy solution would be to adjust the first query. You would need to something like on each of those queries.
PhysicalAttributeID = convert(varchar(20), PhysicalAttributeID)
This is the line you have error at:
TRY_CONVERT(varchar, 'No PhysicalAttributeID') AS PhysicalAttributeID
this is incompatible with its matches, like
phlu.ERSPhysicalAttribute_ID AS PhysicalAttributeID
or
cds.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID
or
CDS.ERSCommodity_ERSPhysicalAttribute_ID AS PhysicalAttributeID
You will need to convert the numeric values above into varchar to solve your problem.
I wanted to write an sql query to fetch data as:
1. when param = 'all' it should list data across the table
2. when param = 'yes' it should list data where invoicenumber is not empty.
3. when param = 'no' it should list data where invoicenumber is empty.
i tried below query for yes and no
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced = 'yes') or (InvoiceNumber = ''))
and
((#invoiced = 'no') or (InvoiceNumber <> ''))
now i also want to incorporate all condition, could anyone suggest how could i achieve that
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
#invoiced = 'all'
OR
(#invoiced = 'yes' AND InvoiceNumber <> '')
OR
(#invoiced = 'no' AND InvoiceNumber = '')
Try this
declare #invoiced as nvarchar(10) = 'no'
select
*
from OrderSummary
where
(
#invoiced = 'all'
OR
(
#invoiced = 'yes'
AND
InvoiceNumber <> ''
)
OR
(
#invoiced = 'no'
AND
InvoiceNumber = ''
)
)
It should fulfill your requirement.
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced in ('all','no')) OR (#invoiced = 'yes' AND InvoiceNumber <> ''))
and
((#invoiced in ('all','yes')) OR (#invoiced = 'no' AND InvoiceNumber = ''))
and
(#invoiced in ('no','yes'))
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced = 'yes') and (InvoiceNumber <> '') )
or
((#invoiced = 'no') and ( (InvoiceNumber = '') or (InvoiceNumber = null)))
or (#invoiced = 'all')
Please update this query with above query.
I want to send an email based on "if body content true send / false don't send"
It doesn't have to be that it can be if there's something returned send if nothing returned don't send.
My code is based on a post from : https://dba.stackexchange.com/questions/83776/need-to-send-a-formatted-html-email-via-database-mail-in-sql-server-2008-r2
If you find this code a bit of a mess its the one the question owner accepted as the best answer at the above link.
Using MS SQL Server 2014
SET #Body = ( SELECT td = CONVERT(VARCHAR(10), P.Date, 120), '',
td = P.ID, '',
td = P.ID2, '',
td = G.ID, '',
td = D.ID,'',
td = D.Name,'',
td = CASE WHEN G.SubmittedDate IS NULL THEN 'New'
ELSE 'Dealer Submitted'
END, ''
FROM I_CancelledGRN I
INNER JOIN TxnGRN G ON G.ID = I.ID
INNER JOIN Distributor D ON D.UID = G.DistributorUID
INNER JOIN POTxn P ON P.SiteUID = G.POTxn_SiteUID
AND P.UID = G.POTxnUID
WHERE IsCancelled IS NULL
FOR XML RAW('tr'),
ELEMENTS
)
SELECT #Body = #TableHead + ISNULL(#Body, '') + #TableTail
EXEC sp_send_dbmail
#profile_name='DatabaseEmailProfile',
#copy_recipients ='aasc#stackexchange.com',
#recipients='aa.sc#outlook.com'
#subject='Query Result',
#body=#Body ,
#body_format = 'HTML' ;
Would something like this work for you?
SET #Body = ( SELECT td = CONVERT(VARCHAR(10), P.Date, 120), '',
td = P.ID, '',
td = P.ID2, '',
td = G.ID, '',
td = D.ID,'',
td = D.Name,'',
td = CASE WHEN G.SubmittedDate IS NULL THEN 'New'
ELSE 'Dealer Submitted'
END, ''
FROM I_CancelledGRN I
INNER JOIN TxnGRN G ON G.ID = I.ID
INNER JOIN Distributor D ON D.UID = G.DistributorUID
INNER JOIN POTxn P ON P.SiteUID = G.POTxn_SiteUID
AND P.UID = G.POTxnUID
WHERE IsCancelled IS NULL
FOR XML RAW('tr'),
ELEMENTS
)
IF LEN(#Body) > 0
BEGIN
SELECT #Body = #TableHead + ISNULL(#Body, '') + #TableTail
EXEC sp_send_dbmail
#profile_name='DatabaseEmailProfile',
#copy_recipients ='aasc#stackexchange.com',
#recipients='aa.sc#outlook.com'
#subject='Query Result',
#body=#Body ,
#body_format = 'HTML' ;
END
It just checks weather #Body has any length at all, and only sends the mail if it does. You can use any other evaluation instead of LEN depending on your scenario