How to create view from the given set of code - sql-server

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.

Related

Sql Server View : Conversion failed when converting the varchar value 'No PhysicalAttributeID' to data type int

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.

Prepare WHERE Clause string for given values

I have the following details to prepare string as shown below in the expected result.
Given:
DECLARE #VValue VARCHAR(MAX) = 'John Dee|Mak Don'
DECLARE #VColumns VARCHAR(MAX) = 'FName|LName'
DECLARE #VCondition VARCHAR(500) = 'OR'
DECLARE #VPattern VARCHAR(MAX) = 'Start|Exact'
DECLARE #VCheck VARCHAR(MAX) = '1|0'
DECLARE #String VARCHAR(MAX) = ''
Expected result:
(
ISNULL(PATINDEX(''John%'', FName), ''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'', FName), ''0'') > 0
)
OR
(
ISNULL(PATINDEX(''Mak'', LName), ''0'') +
ISNULL(PATINDEX(''Don'', LName), ''0'') > 0
)
My attempt:
SET #VCondition = '|'+#VCondition;
SET #String = REPLACE('('+REPLACE(STUFF((SELECT N') '+DS3.Item+' (' + NCHAR(10) +
STUFF((SELECT
CASE WHEN DS4.Item = 'Start' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Start' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE
''
END
+
CASE WHEN DS4.Item = 'Exact' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Exact' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE ''
END
FROM dbo.f_split(DS1.Item,' ') DSn
CROSS APPLY dbo.f_split(DS2.Item,',') DSc
ORDER BY DSc.id, DSn.id
FOR XML PATH(N'')),1,4,N'')
FROM dbo.udf_split (#VValue,'|') DS1
CROSS APPLY dbo.udf_split (#VColumns,'|') DS2
CROSS APPLY dbo.udf_split (#VCondition,'|') DS3
CROSS APPLY dbo.udf_split (#VPattern,'|') DS4
CROSS APPLY dbo.udf_split (#VCheck, '|') DS5
WHERE DS1.id = DS2.id AND DS2.ID = DS3.ID AND DS3.ID = DS4.ID AND DS4.ID = DS5.ID
ORDER BY DS1.id
FOR XML PATH(N'')),1,9,N''),'>','>') + N') )','&gt;','>');
PRINT(#String);
But I'm getting the following result:
( AND
ISNULL(PATINDEX(''John%'', FName), ''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'', FName), ''0'')) OR (
ISNULL(PATINDEX(''Mak'', LName), ''0'') +
ISNULL(PATINDEX(''Don'', LName), ''0'')) )
After many attempt, following does the job done.
Query:
DECLARE #VValue VARCHAR(MAX) = 'John Dee|Mak Don'
DECLARE #VColumns VARCHAR(MAX) = 'FName|LName'
DECLARE #VCondition VARCHAR(500) = 'OR'
DECLARE #VPattern VARCHAR(MAX) = 'Start|Exact'
DECLARE #VCheck VARCHAR(MAX) = '1|0'
DECLARE #String VARCHAR(MAX) = ''
SET #VCondition = '|'+#VCondition;
SET #String = REPLACE('('+STUFF((SELECT N' > 0 ) '+DS3.Item+' (' + NCHAR(10) +
REPLACE(STUFF((SELECT
CASE WHEN DS4.Item = 'Start' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Start' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE
''
END
+
CASE WHEN DS4.Item = 'Exact' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Exact' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE ''
END
FROM dbo.f_split(DS1.Item,' ') DSn
CROSS APPLY dbo.f_split(DS2.Item,',') DSc
ORDER BY DSc.id, DSn.id
FOR XML PATH(N'')),1,11,N''),'>','>')
FROM dbo.udf_split (#VValue,'|') DS1
CROSS APPLY dbo.udf_split (#VColumns,'|') DS2
CROSS APPLY dbo.udf_split (#VCondition,'|') DS3
CROSS APPLY dbo.udf_split (#VPattern,'|') DS4
CROSS APPLY dbo.udf_split (#VCheck, '|') DS5
WHERE DS1.id = DS2.id AND DS2.ID = DS3.ID AND DS3.ID = DS4.ID AND DS4.ID = DS5.ID
ORDER BY DS1.id
FOR XML PATH(N'')),1,13,N''),'>','>') + N' > 0 ) ';
PRINT(#String);
Output:
(
ISNULL(PATINDEX(''John%'',FName),''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'',FName),''0'') > 0
)
OR
(
ISNULL(PATINDEX(''Mak'',LName),''0'') +
ISNULL(PATINDEX(''Don'',LName),''0'') > 0
)

Boolean conditions in SQL where clause

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.

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