what is mean by select * from ... where 1=condition in sql - sql

I have seen in sql procedures: select * from table 1=1
SELECT DISTINCT b.book_number AS book_number,
b.book_title AS b.nook_title,
o.order_summary AS order_summary,
otm.total_amt
FROM books b(nolock)
INNER JOIN books_detail bd (nolock)
ON b.b_id = bd.b_id
INNER JOIN order o(nolock)
ON o.author_id = b.author_id
INNER JOIN order_master otm(nolock)
ON otm.order_number = otm.order_number
WHERE b.status = 'AVAILABLE'
AND ( otm.cnt > 4
OR otm.total > 150
OR 1 = ( CASE
WHEN #order = 'Any' THEN 0
WHEN #order = 'devotional' THEN 1
WHEN #order = 'investigation' THEN 1
ELSE 0
END ) )
my question here is what is the use of
OR 1 = ( CASE
WHEN #order = 'Any' THEN 0
WHEN #order = 'devotional' THEN 1
WHEN #order = 'investigation' THEN 1
ELSE 0
END ) )

If you follow the logical process flow you will see that the result of the case expression is either a 1 or 0 and the where clause is checking to see if 1 is returned.
In this particular instance, the expression is equivalent to:
#order in ('devotional', 'investigation')

Related

Else if in my select statement

I want to have an else if in my select statement i have already tried using case when but the results are not so accurate
heres a snippet of my scripts
select distinct t.MovementDate, t.ContractMovementID, t.GID,t.ReferenceGID,
p.refno, t.amount,convert(date,t.CreatedDate) as createdDat
from
LIF_MGM_T_Contract p
inner join LIF_MMS_T_PolicySuspense s with (nolock)
on s.ContractGID = p.GID
inner join LIF_TMS_T_FinancialTransaction t with (nolock)
on t.ContractGID = p.GID
where
p.refno = '1030642 - 1 - Mohahlaula'
and t.ReversedIndicator = 1
and t.counter = (select min(counter)
from LIF_TMS_T_FinancialTransaction t2 with (nolock)
where t2.ContractGID = p.GID
and t2.ReversedIndicator = 1
and t2.MovementDate = t.MovementDate )
So i want a else if t2.reversedindicator = 0 and date = getdate() return results.. Hope this makes sense

Stored procedure looping error

I'm new to stored procedures and I'm getting an error:
Subquery returned more than 1 value. This is not permitted when the subquery follows
E_R_Main is header table, E_R_Detail is detail table. Both tables are joined using R_ID.
My expected output :
Code:
DECLARE #LALA NVARCHAR(10);
DECLARE #LALA2 NVARCHAR(10);
CREATE TABLE #TEMP
(
EMP_NAME nvarchar(256),
Total_Pending nvarchar(256),
Reschedule_Task nvarchar(256),
New_Task nvarchar(256)
)
--select * from #TEMP
INSERT INTO #TEMP(EMP_NAME, Total_Pending)
SELECT DISTINCT(PIC), COUNT(PIC) AS COUNTTT
FROM E_R_DetailT A
INNER JOIN E_R_MainT b ON a.R_ID = b.R_ID
WHERE PIC IS NOT NULL
GROUP BY T_EMP_ID
SET #LALA = (SELECT COUNT(B.R_ID) AS TEXSST
FROM E_R_MainT A
INNER JOIN E_R_DetailT B ON A.R_ID = B.R_ID
WHERE (b.R_Y = '[Redo]' OR R_Y_N = '[r]')
AND (STAT = 'S_5' OR STAT = 'S_3')
GROUP BY T_EMP_ID )
SET #LALA2 = (SELECT DISTINCT(B.T_EMP_ID)
FROM E_R_MainT A
INNER JOIN E_R_DetailT B ON A.R_ID = B.R_ID
WHERE (b.R_Y = '[Redo]' OR R_Y_N = '[r]')
AND (STAT = 'S_5' OR STAT = 'S_3')
GROUP BY T_EMP_ID)
UPDATE #TEMP
SET Reschedule_Task = #LALA
WHERE #TEMP.EMP_NAME = #LALA2
--SELECT * FROM #TEMP
SELECT
B.Name, a.Total_Pending, New_Task,
CASE
WHEN Reschedule_Task IS NULL
THEN 0
ELSE Reschedule_Task
END AS User_Feedback
FROM
#TEMP A
INNER JOIN
UserInfo B ON A.EMP_NAME = B.EmployeeNo
DROP TABLE #TEMP
Your code seems way more complicated than needed to solve this problem. It looks like a JOIN with conditional aggregation:
select d.pic,
sum(case when m.status in ('S_1', 'S_3', 'S_4') then 1 else 0 end) as Pending,
sum(case when m.status = 'S_1' then 1 else 0 end) as New,
sum(case when m.status = 'S_3' then 1 else 0 end) as Reschedule,
sum(case when m.status = 'S_4' then 1 else 0 end) as Completed
from e_r_main m join
e_r_detail d
on m.r_id = d.r_id
group by d.pic;

How can I optimize the SQL query?

I have a query an SQL query as follows, can anybody suggest any optimization for this; I think most of the effort is being done for the Union operation - is there anything else can be done to get the same result ?
Basically I wanna query first portion of the UNION and if for each record there is no result then the second portion need to be run. Please help.
:
SET dateformat dmy;
WITH incidentcategory
AS (
SELECT 1 ord, i.IncidentId, rl.Description Category FROM incident i
JOIN IncidentLikelihood l ON i.IncidentId = l.IncidentId
JOIN IncidentSeverity s ON i.IncidentId = s.IncidentId
JOIN LikelihoodSeverity ls ON l.LikelihoodId = ls.LikelihoodId AND s.SeverityId = ls.SeverityId
JOIN RiskLevel rl ON ls.RiskLevelId = rl.riskLevelId
UNION
SELECT 2 ord, i.incidentid,
rl.description Category
FROM incident i
JOIN incidentreportlikelihood l
ON i.incidentid = l.incidentid
JOIN incidentreportseverity s
ON i.incidentid = s.incidentid
JOIN likelihoodseverity ls
ON l.likelihoodid = ls.likelihoodid
AND s.severityid = ls.severityid
JOIN risklevel rl
ON ls.risklevelid = rl.risklevelid
) ,
ic AS (
SELECT ROW_NUMBER() OVER (PARTITION BY i.IncidentId ORDER BY (CASE WHEN incidentTime IS NULL THEN GETDATE() ELSE incidentTime END) DESC,ord ASC) rn,
i.incidentid,
dbo.Incidentdescription(i.incidentid, '',
'',
'', '')
IncidentDescription,
dbo.Dateconverttimezonecompanyid(closedtime,
i.companyid)
ClosedTime,
incidenttime,
incidentno,
Isnull(c.category, '')
Category,
opencorrectiveactions,
reportcompleted,
Isnull(classificationcompleted, 0)
ClassificationCompleted,
Cast (( CASE
WHEN closedtime IS NULL THEN 0
ELSE 1
END ) AS BIT)
IncidentClosed,
Cast (( CASE
WHEN investigatorfinishedtime IS NULL THEN 0
ELSE 1
END ) AS BIT)
InvestigationFinished,
Cast (( CASE
WHEN investigationcompletetime IS NULL THEN 0
ELSE 1
END ) AS BIT)
InvestigationComplete,
Cast (( CASE
WHEN investigatorassignedtime IS NULL THEN 0
ELSE 1
END ) AS BIT)
InvestigatorAssigned,
Cast (( CASE
WHEN (SELECT Count(*)
FROM incidentinvestigator
WHERE incidentid = i.incidentid
AND personid = 1588
AND tablename = 'AdminLevels') = 0
THEN 0
ELSE 1
END ) AS BIT)
IncidentInvestigator,
(SELECT dbo.Strconcat(osname)
FROM (SELECT TOP 10 osname
FROM incidentlocation l
JOIN organisationstructure o
ON l.locationid = o.osid
WHERE incidentid = i.incidentid
ORDER BY l.locorder) loc)
Location,
Isnull((SELECT TOP 1 teamleader
FROM incidentinvestigator
WHERE personid = 1588
AND tablename = 'AdminLevels'
AND incidentid = i.incidentid), 0)
TeamLeader,
incidentstatus,
incidentstatussearch
FROM incident i
LEFT OUTER JOIN incidentcategory c
ON i.incidentid = c.incidentid
WHERE i.isdeleted = 0
AND i.companyid = 158
AND incidentno <> 0
--AND reportcompleted = 1
--AND investigatorassignedtime IS NOT NULL
--AND investigatorfinishedtime IS NULL
--AND closedtime IS NULL
),
ic2 AS (
SELECT * FROM ic WHERE rn=1
)
SELECT * FROM ic2
--WHERE rownumber >= 0
-- AND rownumber < 0 + 10
--WHERE ic2.incidentid in(53327,53538)
--WHERE ic2.incidentid = 53338
ORDER BY incidentid DESC
Following is the execution plan I got:
https://www.dropbox.com/s/50dcpelr1ag4blp/Execution_Plan.sqlplan?dl=0
There are several issues:
1) use UNION ALL instead of UNION ALL to avoid the additional operation to aggregate the data.
2) try to modify the numerous function calls (e.g. dbo.Incidentdescription() ) to be an in-lie table valued function so you can reference it using CROSS APPLY or OUTER APPLY. Especially, if those functions referencing a table again.
3) move the subqueries from the SELECT part of the query to the FROM part using CROSS APPLY or OUTER APPLY again.
4) after the above is done, check the execution plan again for any missing indexes. Also, run the query with STATISTICS TIME, IO on to verify that the number of times a table
is referenced is correct (sometimes the execution plan put you in the wrong direction, especially if function calls are involved)...
Since the first inner query produces rows with ord=1 and the second produces rows with ord=2, you should use UNION ALL instead of UNION. UNION will filter out equal rows and since you will never get equal rows it is more efficient to use UNION ALL.
Also, rewrite your query to not use the WITH construct. I've had very bad experiences with this. Just use regular derived tables instead. In the case the query is still abnormally slow, try to serialize some derived tables to a temporary table and query the temporary table instead.
Try alternate approach by removing
(SELECT dbo.Strconcat(osname)
FROM (SELECT TOP 10 osname
FROM incidentlocation l
JOIN organisationstructure o
ON l.locationid = o.osid
WHERE incidentid = i.incidentid
ORDER BY l.locorder) loc)
Location,
Isnull((SELECT TOP 1 teamleader
FROM incidentinvestigator
WHERE personid = 1588
AND tablename = 'AdminLevels'
AND incidentid = i.incidentid), 0)
TeamLeader
from the SELECT. Avoid using complex functions/sub-queries in select.

How can I add a sub-query to this cursor?

I tried to add a sub query (StoCount) to the following cursor:
DECLARE trans_cur CURSOR FOR
SELECT b.TransportNumber,
SUM(CASE WHEN a.DeliveryItemStatus = 'C' OR a.DeliveryItemStatus = 'V' THEN 1 ELSE 0 END) AS Completed,
COUNT(*) AS Total,
SUM(CASE WHEN a.DeliveryItemStatus = 'F' THEN 1 ELSE 0 END) AS Missing,
(SELECT COUNT(*) FROM StorageTransportOrderItem WHERE DeliveryNumber = a.DeliveryNumber AND DeliveryItemNumber = a.DeliveryItemNumber) As StoCount
FROM DeliveryItem a
INNER JOIN TransportItem b on a.DeliveryNumber = b.DeliveryNumber
INNER JOIN Material c on a.MaterialNumber = c.MaterialNumber
INNER JOIN Transport d on b.TransportNumber = d.TransportNumber
WHERE a.StorageLocationNumber IS NOT NULL
AND a.Deleted <> 1
AND c.CommissioningArea LIKE #commissioningArea
AND d.TransportStatus < 70
GROUP BY b.TransportNumber
but when I always get the error message:
Msg 8120, Level 16, State 1, Procedure sp_CalculateTransportProgress,
Line 41 Column 'DeliveryItem.DeliveryNumber' is invalid in the select
list because it is not contained in either an aggregate function or
the GROUP BY clause. Msg 8120, Level 16, State 1, Procedure
sp_CalculateTransportProgress, Line 41 Column
'DeliveryItem.DeliveryItemNumber' is invalid in the select list
because it is not contained in either an aggregate function or the
GROUP BY clause.
My goal is to add this single column (StoCount) to the cursor without modifying the query too much.
Is that possible?
You could move the correlated subquery to a cross apply
SELECT b.TransportNumber,
SUM(CASE WHEN a.DeliveryItemStatus = 'C' OR a.DeliveryItemStatus = 'V' THEN 1 ELSE 0 END) AS Completed,
COUNT(*) AS Total,
SUM(CASE WHEN a.DeliveryItemStatus = 'F' THEN 1 ELSE 0 END) AS Missing,
MAX(e.Freq) AS StoCount
FROM DeliveryItem a
INNER JOIN TransportItem b on a.DeliveryNumber = b.DeliveryNumber
INNER JOIN Material c on a.MaterialNumber = c.MaterialNumber
INNER JOIN Transport d on b.TransportNumber = d.TransportNumber
CROSS APPLY (
SELECT COUNT(*) freq FROM StorageTransportOrderItem s
WHERE s.DeliveryNumber = a.DeliveryNumber AND s.DeliveryItemNumber = a.DeliveryItemNumber
) e
WHERE a.StorageLocationNumber IS NOT NULL
AND a.Deleted <> 1
AND c.CommissioningArea LIKE #commissioningArea
AND d.TransportStatus < 70
GROUP BY b.TransportNumber
Edit by xsl:
I had to modify the query a bit, so that it returned the correct results for my database:
SELECT b.TransportNumber,
SUM(CASE WHEN a.DeliveryItemStatus = 'C' OR a.DeliveryItemStatus = 'V' THEN 1 ELSE 0 END) AS Completed,
COUNT(*) AS Total,
SUM(CASE WHEN a.DeliveryItemStatus = 'F' THEN 1 ELSE 0 END) AS Missing,
SUM(e.Freq) AS StoCount
FROM DeliveryItem a
INNER JOIN TransportItem b on a.DeliveryNumber = b.DeliveryNumber
INNER JOIN Material c on a.MaterialNumber = c.MaterialNumber
INNER JOIN Transport d on b.TransportNumber = d.TransportNumber
CROSS APPLY (
SELECT COUNT(1) freq FROM StorageTransportOrderItem s
WHERE
s.DeliveryNumber = a.DeliveryNumber
AND s.DeliveryItemNumber = a.DeliveryItemNumber
AND s.MaterialNumber = a.MaterialNumber
) e
WHERE a.StorageLocationNumber IS NOT NULL
AND a.Deleted <> 1
AND c.CommissioningArea LIKE #commissioningArea
AND d.TransportStatus < 70
GROUP BY b.TransportNumber

How to add 2 numbers in sql Select clause?

I have this query:
Select
Count(DocumentID)
From
Documents d
Inner Join
Accounts a on a.AccountID = d.CreatedByAccountID
Where
a.FeeExempt = 1
Or
(Select
Case
When a.OrganizationTypeID = 1 Or a.OrganizationTypeID = 2
Then 0
Else EFileFee
End
From ITypes
Where ITypeID = d.ITypeID
+
Select 100 --just to test
) <= 0
How can I make this query compile? Basically I want to do 2 selects and check if addition of both of them is less than 0 or not. But obviously at the moment the query is incorrect and won't compile.
Do you want this:
. . ..
(select sum(val)
from ((Select (Case When a.OrganizationTypeID = 1 Or a.OrganizationTypeID = 2 Then 0 Else EFileFee End) as val
From ITypes
Where ITypeID = d.ITypeID
) union all
(Select 100 --just to test
)
) t
) <= 0