My query takes a long time - sql-server

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.

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.

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.

SQL Logic to validate Parameter

I have parameter on sql , and I got an issue when it comes to this situation
declare #MonRemark varchar(10) = 's'
declare #ConfBy varchar(10)= 's'
declare #confstatus varchar(10)= 's'
declare #StatGD varchar(10)= ''
declare #StatGC varchar(50)= ''
declare #STATGTWO varchar(50)= ''
IF #MonRemark <> '' and (#ConfBy = '' OR #confstatus = '' and (#StatGD = '' or #StatGC = '' or #STATGTWO = '')) BEGIN
print 'a'
END
ELSE IF #ConfBy <> '' and (#MonRemark = '' OR #confstatus = '' AND (#StatGD = '' or #StatGC = '' or #STATGTWO = '')) BEGIN
print 'b'
END
ELSE IF #confstatus <> '' and #MonRemark = '' AND #ConfBy = '' AND (#StatGD = '' or #StatGC = '' or #STATGTWO = '') BEGIN
print 'c'
END
ELSE IF (#StatGD <> '' or #StatGC <> '' or #STATGTWO <> '') and #confstatus = '' AND #MonRemark = '' AND #ConfBy = '' BEGIN
print 'd'
END
ELSE BEGIN
print 'e'
END
if I filled parameter like what I write Above, I wish to get A , but it's always print E, is there any way to get A?
Change your condition. I think #Cyan and #JTR has provided enough explanation on why you get the value 'e'
Try like this, I have modified your condition to get the required results.
DECLARE #MonRemark VARCHAR(10) = 's'
DECLARE #ConfBy VARCHAR(10) = 's'
DECLARE #confstatus VARCHAR(10) = 's'
DECLARE #StatGD VARCHAR(10) = ''
DECLARE #StatGC VARCHAR(50) = ''
DECLARE #STATGTWO VARCHAR(50) = ''
IF #MonRemark <> ''
AND (
(
#ConfBy = ''
OR #confstatus = ''
)
OR (
#StatGD = ''
OR #StatGC = ''
OR #STATGTWO = ''
)
)
BEGIN
PRINT 'a'
END
ELSE IF #ConfBy <> ''
AND (
#MonRemark = ''
OR #confstatus = ''
AND (
#StatGD = ''
OR #StatGC = ''
OR #STATGTWO = ''
)
)
BEGIN
PRINT 'b'
END
ELSE IF #confstatus <> ''
AND #MonRemark = ''
AND #ConfBy = ''
AND (
#StatGD = ''
OR #StatGC = ''
OR #STATGTWO = ''
)
BEGIN
PRINT 'c'
END
ELSE IF (
#StatGD <> ''
OR #StatGC <> ''
OR #STATGTWO <> ''
)
AND #confstatus = ''
AND #MonRemark = ''
AND #ConfBy = ''
BEGIN
PRINT 'd'
END
ELSE
BEGIN
PRINT 'e'
END

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