How to use case statement inside where clause of sql 2000 - sql

I have a query that contains a WHERE clause with a CASE statement in it (See code below), somehow it doesn't seem to work.
select * FROM
details
where orgcode in
(case when orgtype='P' then
(SELECT distinct [PCode]
FROM [GPOS_Extract].[dbo].[GP8288List])
else
0 end )

How about
select * FROM details
where (orgtype <> 'P' AND orgcode = 0)
or orgcode in
(
SELECT distinct [PCode]
FROM [GPOS_Extract].[dbo].[GP8288List]
)

Or try this:
SELECT * FROM details
WHERE details.orgcode IN
( SELECT DISTINCT
(CASE WHEN details.orgtype='P'
THEN [GPOS_Extract].[dbo].[GP8288List].PCode
ELSE 0 END)
FROM [GPOS_Extract].[dbo].[GP8288List] )

I think the following is the logic that is equivalent to your attempt:
select *
FROM details
where (orgtype = 'P' and
orgcode in (SELECT distinct [PCode]
FROM [GPOS_Extract].[dbo].[GP8288List]
)
) or
((orgtype <> 'P' or orgtype is NULL) and orgcode = 0);

what about this,
select a.*,case when orgtype='P' then PCode else '0' end FROM
details a
left join [GPOS_Extract].[dbo].[GP8288List] b on a.orgcode=b.PCode

case returns a single value. You are trying to use it as though it returns a result set. What you want is:
select * FROM details d
where (orgtype = 'p'
And exists (Select *
From GPOS_Extract.dbo.GP8288List
Where PCode = d.orgcode))
or (orgtype <> 'p' And orgcode= 0)

Related

Case expression with subquery error: coud not be bound

I'm trying to use a Case Expression when a I have a subquery, and SQL keeps me returning
The multi-part identifier "local1.DescricaoLotacao" could not be
bound.
CASE WHEN (SELECT local1.[DescricaoLotacao] FROM sgp.dbo.[LOTACAO] AS [local1]
WHERE local1.IdLotacao = (SELECT TOP 1 [uai].[IdLotacao] FROM sgp.dbo.[UnidadeAdministrativaInterna] AS [uai]
WHERE uai.[CodigoPessoal] = p.[CodigoPessoal] AND uai.[DataFinal] IS NULL ORDER BY [uai].[DataInicial] DESC)
) IS NOT NULL
THEN local1.[DescricaoLotacao]
ELSE ''
END,
I know it's why my local.descricaoLotacao is out of my parentheses. But I don't know how to fix it. I thing there is another way to do this kind of select.
If you are sure that the query will return only 1 row then instead of CASE use COALESCE():
COALESCE(
(
SELECT local1.[DescricaoLotacao] FROM sgp.dbo.[LOTACAO] AS [local1]
WHERE local1.IdLotacao = (
SELECT TOP 1 [uai].[IdLotacao]
FROM sgp.dbo.[UnidadeAdministrativaInterna] AS [uai]
WHERE uai.[CodigoPessoal] = p.[CodigoPessoal] AND uai.[DataFinal] IS NULL
ORDER BY [uai].[DataInicial] DESC
),
''
)
I suggest using EXISTS
This is assuming the local1.[DescricaoLotacao] portion exists outside of the CASE WHEN section.
CASE WHEN EXISTS (SELECT local1.[DescricaoLotacao] FROM sgp.dbo.[LOTACAO] AS [local1]
WHERE local1.IdLotacao = (SELECT TOP 1 [uai].[IdLotacao] FROM sgp.dbo.[UnidadeAdministrativaInterna] AS [uai]
WHERE uai.[CodigoPessoal] = p.[CodigoPessoal] AND uai.[DataFinal] IS NULL ORDER BY [uai].[DataInicial] DESC)
)
THEN local1.[DescricaoLotacao]
ELSE ''
END

T-sql run 1st query and then CASE 2nd query and output data or 'No'

Hey all I am trying to output data if the #blah equals Yes but output 'No' if not.
This is my current query:
DECLARE #blah VARCHAR(MAX)
SET #blah = (SELECT
CASE WHEN
COUNT(email) = '1' THEN 'Yes'
ELSE 'No'
END
FROM
usersTbl
WHERE
email = 'someone#somewhere.com');
SELECT
CASE WHEN
#blah = 'Yes' THEN
(SELECT *
FROM
usersTbl
WHERE
email = 'someone#somewhere.com')
ELSE 'No'
END
FROM
usersTbl;
Currently the error I am getting with the above is:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
What am I missing?
You could use EXISTS here instead. Something like this.
if exists
(
SELECT *
FROM
usersTbl
WHERE
email = 'someone#somewhere.com'
)
SELECT *
FROM
usersTbl
WHERE
email = 'someone#somewhere.com'
ELSE
select 'No'

SQL Server sum and subtract prevent null results

I'm using this code:
SELECT
(SELECT SUM(TrnQty) AS Total
FROM InventoryTrans
WHERE InventoryItemID = (select MAX(InventoryItemID)
from inventorymaster)
AND CustomerID = '0') -
(SELECT SUM(TrnQty) AS Total
FROM InventoryTrans
WHERE InventoryItemID = (select MAX(InventoryItemID)
from InventoryMaster)
AND CustomerID > '0'
)
If the result of one them is NULL i take totally result NULL. How can I SUM if one of them is Null? Should I use CASE or something?
Here is a correct way to do it
SELECT Sum(CASE
WHEN customerid = '0' THEN trnqty
ELSE 0
END) - Sum(CASE
WHEN customerid > '0' THEN trnqty
ELSE 0
END) AS Total
FROM inventorytrans
WHERE inventoryitemid = (SELECT Max (inventoryitemid)
FROM inventorymaster)
EDIT:
I [#GordonLinoff] am providing a slightly simpler version of this answer. The use of conditional aggregation is correct, but there is a simpler way of writing it:
SELECT SUM(CASE WHEN it.customerid = '0' THEN it.trnqty
WHEN it.customerid > '0' THEN - it.trnqty
ELSE 0
END) as Total
FROM inventorytrans it
WHERE it.inventoryitemid = (SELECT Max(im.inventoryitemid)
FROM inventorymaster im
)
use
SELECT coalesce(SUM(TrnQty), 0) ...
You can also use
SELECT ISNULL(SUM(TrnQty),0)...
Simply wrap your existing inner select statements in an ISNULL function. It is simple to implement and your intent is clear, if your SELECT returns a null value, use 0.
SELECT
IsNull(
(
SELECT SUM(TrnQty) AS Total
FROM InventoryTrans
WHERE InventoryItemID =
(
select MAX (InventoryItemID) from inventorymaster
)
and CustomerID='0'
),0) -
IsNull(
(
SELECT SUM(TrnQty) AS Total
FROM InventoryTrans
WHERE InventoryItemID =
(
select MAX (InventoryItemID) from InventoryMaster
)
and CustomerID > '0'
),0)
Is this a great example of SQL, not really, but you can see how wrapping the select statements with IsNull is a minor change to your existing query to give you the results you need.
This query could be re-written into a single set based operation, here's my go at it:
SELECT SUM(CASE customerid WHEN '0' THEN -TrnQty ELSE TrnQty END) AS Total
FROM InventoryTrans
WHERE InventoryItemID =
(
select MAX (InventoryItemID) from inventorymaster
)
It is not necessary in this new query to check for null, (either with IsNull or Coalesce) unless you need to ensure that the end result is not null, this query will only return null if ALL of the TrnQty fields are also null. If that is a problem for you logic, wrap the SUM function in an IsNull function as well.

How to use Select Exists in Oracle?

What is the equivalent of the below SQL Query in Oracle?
SELECT CAST(
CASE WHEN EXISTS(SELECT * FROM theTable where theColumn like 'theValue%') THEN 1
ELSE 0
END
AS BIT)
I just want an oracle query where exists is used and it returns 0 or 1 like above.
The equivalent would be:
select count(*)
from dual
where exists (SELECT * FROM theTable where theColumn like 'theValue%')
This would show the same output. Just removed the CAST and added a FROM dual as Oracle doesn't allow queries with SELECT and without FROM:
SELECT
CASE WHEN EXISTS(SELECT * FROM theTable where theColumn like 'theValue%')
THEN 1
ELSE 0
END
FROM dual ;
Tested at SQL-Fiddle
You could write it:
SELECT COUNT(*) FROM theTable WHERE theColumn LIKE 'theValue%' AND ROWNUM = 1
This will return 0-1 and the optimizer gets that the query is to be optimized for first-row access.
You could also use MAX with CASE:
SELECT MAX(
CASE
WHEN theColumn like 'theValue%' THEN 1
ELSE
0
END)
AS BIT
FROM theTable
You can use one of the following queries: (the first ones is more performant)
SELECT H.TABLE_ID, H.OTHER_FIELD,
(SELECT 'YES' FROM DUAL WHERE EXISTS (SELECT 'X' FROM TABLE_DETAIL DT
WHERE DT.TABLE_ID = H.TABLE_ID) ) WITH_DETAIL FROM TABLE_HEADER H;
SELECT H.TABLE_ID, H.OTHER_FIELD,
CASE WHEN EXISTS(SELECT * FROM IMTS.DETAIL_TABLE DT WHERE DT.TABLE_ID=H.TABLE_ID)
THEN 'Y' ELSE 'N' END WITH_DETAIL FROM HEADER_TABLE H;
SELECT H.TABLE_ID, H.OTHER_FIELD, NVL2(DT.SOME_NOTNULL_FIELD, 'YES','NO') WITH_DETAIL
FROM TABLE_HEADER H
LEFT JOIN TABLE_DETAIL DT ON DT.TABLE_ID=H.TABLE_ID AND ROWNUM<2;

select inside case statement in where clause tsql

I have written a case condition inside where clause which is working fine without any sub queries, but it is not working with sub queries
for example
declare #isadmin varchar(5) = 'M'
select * from Aging_calc_all a where a.AccountNumber in
(case #isadmin when 'M' then 1 else 0 end)
which is working fine.
However this does not seem to work -
select * from Aging_calc_all a where a.AccountNumber in
(case #isadmin when 'M' then (select AccountNumber from ACE_AccsLevelMaster where AssignedUser=7) else 0 end)
Any suggestions or this is a t-sql bug in 2008.
The error you're receiving is "Subquery returned more than 1 value", I believe. So you can't return multiple values after THEN.
You should rewrite your query to something like this:
select
*
from Aging_calc_all a
where
(#isadmin='M' and a.AccountNumber in (select AccountNumber from ACE_AccsLevelMaster where AssignedUser=7))
or
(#isadmin<>'M' and a.AccountNumber=0)
select * from Aging_calc_all a where a.AccountNumber in (
SELECT AccountNumber
from ACE_AccsLevelMaster
where AssignedUser=7 AND #isadmin = 'M'
UNION ALL select 0 where #isadmin <> 'M'
)
EDITED To show how use multiple criteria
select * from Aging_calc_all a where a.AccountNumber in (
SELECT AccountNumber
from ACE_AccsLevelMaster
where AssignedUser=7 AND #isadmin = 'M'
-- case to select from another table:
UNION ALL select * from ANOTHER_TABLE where #isadmin = 'A'
-- case to select from const set (1, 2, 3):
UNION ALL select * from (
select 1 union all select 2 union all select 3) x where #isadmin = 'B'
-- case to show how 'else' work
UNION ALL select 0 where #isadmin not in( 'M', 'A', 'B')
)
This should work(although it's not a direct answer of the question):
SELECT *
FROM aging_calc_all a
WHERE ( #isadmin <> 'M' AND a.accountnumber = 0 )
OR ( #isadmin = 'M' AND a.accountnumber IN (SELECT accountnumber
FROM ace_accslevelmaster
WHERE assigneduser = 7) )