Boolean conditions in SQL where clause - sql-server

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.

Related

How to create view from the given set of code

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

SQL Server : conditional concatenation

I'm sure there's a better way to do this (SQL Server 2014).
I have 3 columns that represent approval by customer, sales or plant. The values will be 'Yes' or 'No' (3rd party app). I need to abbreviate the selected 'Yes' fields to a separated list of the first initials; for example if Sales and Client are 'Yes' I need to show 'S/C' on a report.
I've done it like this for now, as it was time sensitive, but I'm sure there's a better way:
case
when cfv1.CVFieldValue = 'Yes' and cfv2.CVFieldValue = 'Yes' and cfv3.CVFieldValue = 'Yes'
then 'P/S/C'
when cfv1.CVFieldValue = 'Yes' and cfv2.CVFieldValue = 'Yes' and cfv3.CVFieldValue = 'No'
then 'P/S'
when cfv1.CVFieldValue = 'Yes' and cfv2.CVFieldValue = 'No' and cfv3.CVFieldValue = 'Yes'
then 'P/C'
when cfv1.CVFieldValue = 'No' and cfv2.CVFieldValue = 'Yes' and cfv3.CVFieldValue = 'Yes'
then 'S/C'
when cfv1.CVFieldValue = 'Yes' and cfv2.CVFieldValue = 'No' and cfv3.CVFieldValue = 'No'
then 'P'
when cfv1.CVFieldValue = 'No' and cfv2.CVFieldValue = 'Yes' and cfv3.CVFieldValue = 'No'
then 'S'
when cfv1.CVFieldValue = 'No' and cfv2.CVFieldValue = 'No' and cfv3.CVFieldValue = 'Yes'
then 'C'
when cfv1.CVFieldValue = 'No' and cfv2.CVFieldValue = 'No' and cfv3.CVFieldValue = 'No'
then ''
end as OKBy
Anyone got a better way?
TIA
Mark
1) First solution: you could use a mapping table
SELECT x.*, s.RetValue
FROM dbo.SomeTable x
LEFT JOIN
( -- You could insert bellow values into a temp table / #table variable
-- Warning: following pair of values (CVFieldValue, CVFieldValue2, CVFieldValue3) should be UNIQUE
VALUES
('Yes', 'Yes', 'Yes', 'P/S/C'),
('Yes', 'Yes', 'No', 'P/S'),
('Yes', 'No', 'Yes', 'P/C') --, ...
) map (CVFieldValue1, CVFieldValue2, CVFieldValue3, RetValue)
ON x.CVFieldValue1 = s.CVFieldValue1
AND x.CVFieldValue2 = s.CVFieldValue2
AND x.CVFieldValue3 = s.CVFieldValue3
2) Second solution: IIF and CONCAT (SQL2012+)
SELECT STUFF(
CONCAT(
IIF(CVFieldValue1 = 'Yes', '/P', ''),
IIF(CVFieldValue2 = 'Yes', '/S', ''),
IIF(CVFieldValue3 = 'Yes', '/C', ''),
' ' -- If you remove this line then result will be NULL when all columns have non 'Yes' values
),
1, 1, '') AS Result
,*
FROM (
VALUES
('Yes', 'Yes', 'Yes'),
('Yes', 'Yes', 'No'),
('Yes', 'No', 'Yes'), -- ... Source table
('No', 'No', 'No')
) SomeTable (CVFieldValue1, CVFieldValue2, CVFieldValue3)

Send database email based on "if body content true send / false don't send"

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

Error converting data type varchar to numeric for this below query

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

Reduce multiple if else statement

I have the following 5 variables to check for a condition.
Example:
DECLARE #Col1 VARCHAR(10) = ''
DECLARE #Col2 VARCHAR(10) = ''
DECLARE #Col3 VARCHAR(10) = ''
DECLARE #Col4 VARCHAR(10) = ''
DECLARE #Col5 VARCHAR(10) = ''
DECLARE #String VARCHAR(MAX)
IF #Col1 = '' AND #Col2 = '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = ''
BEGIN
SET #String = ''
END
ELSE IF #Col1 <> '' AND #Col2 = '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = ''
BEGIN
SET #String = '#Col1'
END
ELSE IF #Col1 = '' AND #Col2 <> '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = ''
BEGIN
SET #String = '#Col2'
END
ELSE IF #Col1 = '' AND #Col2 = '' AND #Col3 <> '' AND #Col4 = '' AND #Col5 = ''
BEGIN
SET #String = '#Col3'
END
ELSE IF #Col1 = '' AND #Col2 = '' AND #Col3 = '' AND #Col4 <> '' AND #Col5 = ''
BEGIN
SET #String = '#Col4'
END
.....
.....
.....
As the above conditions show, there are many probabilities.
How can I reduce the occurrences of multiple if conditions?
You can use CASE WHEN:
SELECT #String = CASE
WHEN #Col1 = '' AND #Col2 = '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = '' THEN ''
WHEN #Col1 <> '' AND #Col2 = '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = '' THEN '#Col1'
WHEN #Col1 = '' AND #Col2 <> '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = '' THEN '#Col2'
WHEN #Col1 = '' AND #Col2 = '' AND #Col3 <> '' AND #Col4 = '' AND #Col5 = '' THEN '#Col3'
WHEN #Col1 = '' AND #Col2 = '' AND #Col3 = '' AND #Col4 <> '' AND #Col5 = '' THEN '#Col4'
ELSE NULL
END
SQL Server 2012+:
SELECT #String = COALESCE(IIF(#Col1 <> '', '#Col1', NULL),
IIF(#Col2 <> '', '#Col2', NULL),
IIF(#Col3 <> '', '#Col3', NULL),
IIF(#Col4 <> '', '#Col4', '' ));
EDIT:
DECLARE #Col1 VARCHAR(10) = ''
DECLARE #Col2 VARCHAR(10) = ''
DECLARE #Col3 VARCHAR(10) = ''
DECLARE #Col4 VARCHAR(10) = ''
DECLARE #Col5 VARCHAR(10) = ''
DECLARE #String VARCHAR(MAX) = '';
IF #col1 <> ''
SET #String += '#col1';
IF #col2 <> ''
SET #String += '#col2';
IF #col3 <> ''
SET #String += '#col3';
...
IF #coln <> ''
SET #String += '#coln';
I would like to help as well, sorry for a different approach.
I took your case as something that can be stacked and I arrived at this.
DECLARE #Col1 VARCHAR(10) = 'test'
DECLARE #Col2 VARCHAR(10) = ''
DECLARE #Col3 VARCHAR(10) = 'tet'
DECLARE #Col4 VARCHAR(10) = ''
DECLARE #Col5 VARCHAR(10) = 't'
DECLARE #String VARCHAR(MAX)
CREATE TABLE #cols (ColName NVARCHAR(150), ColVal NVARCHAR(150))
INSERT INTO #cols VALUES ('#Col1',#Col1),('#Col2',#Col2),('#Col3',#Col3),('#Col4',#Col4),('#Col5',#Col5)
-- if you want to just concatenate things without a delimiter, you can do this
SET #String = (SELECT ColName AS [text()] FROM #cols WHERE ColVal != '' FOR XML PATH(''))
SELECT #String
-- output #Col1#Col3#Col5
-- if you want to concatenate things with a delimiter, you can do this
SET #String = (SELECT ColName + ', ' AS [text()] FROM #cols WHERE ColVal != '' FOR XML PATH(''))
SELECT #String
-- output #Col1, #Col3, #Col5
DROP TABLE #cols
Hope this adds something to the idea. Please let me know if you have concerns.
You can do in one statement using case expressions:
SELECT #String = CASE WHEN #Col1 = '' THEN 'col1' ELSE '' END +
CASE WHEN #Col2 = '' THEN 'col2' ELSE '' END +
CASE WHEN #Col3 = '' THEN 'col3' ELSE '' END +
CASE WHEN #Col4 = '' THEN 'col4' ELSE '' END +
CASE WHEN #Col5 = '' THEN 'col5' ELSE '' END

Resources