I have the following working code:
INSERT INTO #resultado
SELECT 1,
v.idReqVoucher,
v.dtSolicitacao,
v.idFuncionario_solicitante,
v.idFuncionario_beneficiario,
v.idStatus,
NULL as valor
FROM reqVoucher v
WHERE
v.idReqVoucher =
CASE WHEN #idRequisicao = 0 THEN v.idReqVoucher
ELSE #idRequisicao END
AND v.idStatus =
CASE WHEN #status = 0 THEN v.idStatus
ELSE #status END
AND v.dtSolicitacao >= CASE WHEN #dtSolicitacaoIni IS NULL THEN v.dtSolicitacao ELSE #dtSolicitacaoIni END
AND v.dtSolicitacao <= CASE WHEN #dtSolicitacaoFim IS NULL THEN v.dtSolicitacao ELSE #dtSolicitacaoFim+' 23:59:59' END
But what I need to achieve is something like that:
AND v.idStatus
CASE WHEN #status = 99 THEN NOT IN (5,1,4,20)
ELSE WHEN #status != 0 THEN = #status END
And I have no idea on how achieve that in my code. I'm fairly new in TSQL and SQL Server, so please be gentle.
Or use a CASE expression:
and case
when #status = 99 and v.idStatus not in ( 5, 1, 4, 20 ) then 1
when #status !=0 and v.idStatus = #status then 1
else 0
end = 1
The CASE expression returns a value which you must then use, e.g. by comparing it to 1. It is generally good practice to include an ELSE clause to supply a default value should the unexpected arise.
The CASE statement returns a value, it does not act as an IF statement by changing the SQL query (if this, then do that). You would need to modify your where statement to something like the following:
AND (
(#status = 99 AND v.idStatus NOT IN (5, 1, 4, 20))
OR (#status NOT IN (0, 99) AND v.idStatus = #status)
)
Edit: Commenter is correct, the 2nd check needs to ensure the #status is not 99.
This should be equivalent to what you want:
AND (
(#status = 99) AND (v.idStatus NOT IN (5,1,4,20))
OR
(#status <> 99) AND (#status <> 0) AND (v.idStatus = #status)
)
CASE expression can only be used to return a scalar value, so it cannot be used to return a predicate like NOT IN (5,1,4,20).
Related
In my select statement I calculate some values and then need to calculate a new value based on the results of the already calculated values. How can this be archived without using a temp table?
SELECT
CASE WHEN [Customer] = '173220000' THEN '1' ELSE NULL END AS Ver_a
, CASE WHEN [Service] = '173220000' THEN '1' ELSE NULL END AS Ver_b
, CASE WHEN [Productavailability] = '173220000' THEN '1' ELSE NULL END AS Ver_c
, (SUM(Ver_a, Ver_b, Ver_c)/3) AS Identity_Ver
FROM x
Just use a sub-query/derived table:
SELECT
Ver_a
, Ver_b
, Ver_c
, (coalesce(Ver_a,0) + coalesce(Ver_b,0) + coalesce(Ver_c,0))/3 AS Identity_Ver
FROM (
SELECT
CASE WHEN [Customer] = '173220000' THEN '1' ELSE NULL END AS Ver_a
, CASE WHEN [Service] = '173220000' THEN '1' ELSE NULL END AS Ver_b
, CASE WHEN [Productavailability] = '173220000' THEN '1' ELSE NULL END AS Ver_c
FROM x
) x
Note 1: as you are not grouping you don't need the sum function, just the sum operator (+) - and the sum function doesn't take a comma separated list of values either.
Note 2: your sum won't work without using the coalesce function as you are returning null from the case expressions.
Firstly, you cannot do sum(var1, var2, var3).
The answer to your question, as stated, seems to be the code at the end.
BUT, I have to ask: what do you want to accomplish? Your approach does make sense to me :-(
SELECT
Sum(
CASE WHEN [customer] = '173220000' THEN 1 ELSE 0 END +
CASE WHEN [service] = '173220000' THEN 1 ELSE 0 END +
CASE WHEN [productavailability] = '173220000' THEN 1 ELSE 0 END
) / 3 AS Identity_Ver
FROM x
I have a select query with where Clause. Now I have to add additional condition in where clause based on user access. If user does not have access then need to include additional condition in where clause, else if user have access then there is no additional logic.
For example:
Select * from TableA where ID > 100
Additional Logic:
If user does not have access to Admin Page then #X= 0 and if does not have access to External Page then #Y = 0.
I need to include the below logic in where clause:
if (#X = 0 and #y=0) then
pagecode not in ('admin','external')
else if(#x=0 and #y=1) then
pagecode not in ('admin')
else if(#x=1 and #y=0) then
pagecode not in ('external')
else
no additional logic in where clause
How to implement this using case in where clause.
You can use CASE in WHERE as Shown below:
WHERE 1=(
CASE WHEN #X = 0 and #y = 0 and pagecode not in ('admin','external') THEN 1
WHEN #x = 0 and #y = 1 and pagecode not in ('admin') THEN 1
WHEN #x = 1 and #y = 0 and pagecode not in ('external') THEN 1
ELSE 0 END
)
this will not return any row if #x=1 and #y=1.
If you want to return all rows if #x=1 and #y=1
WHERE 1=(
CASE WHEN #X = 0 and #y = 0 and pagecode not in ('admin','external') THEN 1
WHEN #x = 0 and #y = 1 and pagecode not in ('admin') THEN 1
WHEN #x = 1 and #y = 0 and pagecode not in ('external') THEN 1
WHEN #x = 1 and #y = 1 THEN 1
ELSE 0 END
)
Pretty sparse on details here. The ELSE is pretty vague but I was assuming that both variables would equal 1. But we don't even know the datatype of those so not totally sure. My guess is something like this.
where
(
#X = 0
and
#y = 0
and pagecode not in ('admin','external')
)
OR
(
#x = 0
and
#y = 1
and
pagecode not in ('admin')
)
OR
(
#x = 1
and
#y = 0
and
pagecode not in ('external')
)
OR
(
#x = 1
and
#y = 1
)
Be warned. This approach can have some serious performance problems. Gail Shaw has written about this here and a follow up here. You can also read Erland Sommarskog's article here
Maybe this:
WHERE ID > 100
AND ((pagecode != 'admin' and X = 0) or X= 1)
AND ((pagecode != 'external' and Y = 0) or Y= 1)
Since the question asks
How to implement this using case in where clause.
I thought I'd do a little experimentation. After discovering some interesting limitations, I found a way.
You should be able to adapt this successful experiment:
SELECT 'boom'
WHERE 'a' NOT IN (
SELECT CASE WHEN 1=0 THEN 'a' ELSE '' END
UNION ALL
SELECT CASE WHEN 1=1 THEN 'b' ELSE '' END
)
Note the ELSE '' is important. Without an ELSE the CASE will supply a NULL for that row, and that will mess up your IN() condition.
By the way, this isn't how I would look to solve your actual problem, but it does answer the question, so if you really need to use a CASE expression for some reason, this is how it can be done.
ALTER PROCEDURE GetVendor_RMA_CreditMemo
(#HasCreditMemoNo INT)
BEGIN
SELECT
*
FROM
(SELECT
CreditMemoNumber,
CASE WHEN CreditMemoNumber != ''
THEN 1
ELSE 0
END AS HasCreditMemoNo
FROM
XYZ) as C
WHERE
(C.HasCreditMemoNo = #HasCreditMemoNo OR #HasCreditMemoNo = -1)
END
CreditMemoNumber is a varchar column
I want to achieve this:
CASE
WHEN #HasCreditMemoNo = 0
THEN -- select all rows with no value in CreditMemoNumber Column,
WHEN #HasCreditMemoNo = 1
THEN -- all rows that has some data,
WHEN #HasCreditMemoNo = -1
THEN -- everything regardless..
You can't do this kind of thing with a CASE.
The correct way to do it is with OR:
WHERE (#HasCreditMemoNo = 0 AND {no value in CreditMemoNumber Column})
OR
(#HasCreditMemoNo = 1 AND {all rows that has some data})
OR
(#HasCreditMemoNo = -1)
Would this work for you? I'm not sure if it would improve your performance. You may be better off writing an if else if else statement and three separate select statements with an index on the CreditMemoNumber column.
ALTER PROCEDURE GetVendor_RMA_CreditMemo(#HasCreditMemoNo int)
BEGIN
select
CreditMemoNumber,
case when CreditMemoNumber != '' then 1 else 0 end as HasCreditMemoNo
from XYZ
where
(#HasCreditMemoNo = 0 and (CreditMemoNumber is null or CreditMemoNumber = ''))
or (#HasCreditMemoNo = 1 and CreditMemoNumber != '')
or (#HasCreditMemoNo = -1)
END
I am creating a store procedure and in which am I stuck in a problem. I want to query two columns based on condition. If parameter is numeric then query to one column and if it is nonnumeric then query to other column. Following is the procedure.
$
declare #result AS varchar(50)
DECLARE #peopleId AS varchar(50)
if('232332' NOT LIKE '%[^0-9]%')
BEGIN
SET #result='Numeric'
PRINT #result
END
ELSE
BEGIN
set #result='nonNumeric'
print #result
END
select isnull(class.grade,'') as grade,ISNULL(class.room,'') as room,student.prefix as prefix,student.student_id as student_id,(person.first_name+' '+person.last_name) as name,
person.dob as dob,person.people_id as people_id,quit_on,
case when student.student_status='30' then
N'พักการเรียน'
when student.student_status='31' then
N'น.ร.ไปเรียนโครงการฯ'
else ''
end
as quit_reason from school_student student
inner join people_person person on student.person_id=person.id
left join school_classroom_students classStudent on classStudent.student_id=student.id
left join school_classroom class on class.id =classStudent.classroom_id
where student.student_status in('30','31') and student.system_status = 'DC' and student.school_id=#schoolId
AND case
WHEN
#result='nonNumeric' then-- this should execure
person.people_id=#peopleId
else---- this should work
person.first_name+' '+ person.last_name LIKE '%'+#peopleId+'%'
Please help me out on this
Why would use use a separate variable? You can do:
WHEN (person.people_id = try_convert(int, #peopleId) or
try_convert(int, #peopleId) is null and
person.first_name + ' ' + person.last_name LIKE '%' + #peopleId + '%'
)
I question why you are passing a value that is used for both a string and numeric comparison. If I were using a variable, I would do:
declare #personid int;
declare #personname varchar(255);
if #peopleid not like '%[^0-9]%'
set #personname = #peopleid;
else
set #personid = convert(int, #peopleid);
where (personid = #personid or
person.first_name + ' ' + person.last_name LIKE '%' + #personname + '%'
)
The code just seems easier to follow.
Since SQL Server doesn't treat results of CASE expressions as booleans, you have to add an extra comparison. The way to do that is like this:
WHERE 1 = CASE WHEN x THEN 1 WHEN y THEN 0 ELSE 1 END
Conditions which result in rows being included in the result must evaluate to 1, and conditions which don't, must evaluate to something other than 1 (like 0). So the whole CASE expression returns either 0 or 1, and that is compared to 1.
In your code, it would look like this:
AND 1 = case
WHEN
#result='nonNumeric' then case when person.person_id = #peopleId then 1 else 0 end
else when person.first_name+' '+person.last_name LIKE '%'+#peopleId+'%' then 1 else 0 end
end
I added the END.
Just do like that
DECLARE #IsNumeric INT = NULL
DECLARE #IsNotNumeric INT = NULL
DECLARE #peopleId Varchar(50)
SET #peopleId = '123'
IF ISNUMERIC(#peopleId) = 1
BEGIN
SET #IsNumeric = 1
END
ELSE
BEGIN
SET #IsNotNumeric = 1
END
IN WHERE Condition Just Check
AND (#IsNumeric IS NULL OR CONVERT(VARCHAR(500),person.people_id)=#peopleId)
AND (#IsNotNumeric IS NULL OR person.first_name+' '+ person.last_name LIKE '%'+#peopleId+'%')
I currently have a select statement that checks several columns to see if they have data. if any of them are null then i want a bit set to false. if none of them are null then i want a bit set to true. here's what i currently have:
select
cast(
case when ChangeOrderNumber is null then 0 else 1 end *
case when ClientName is null then 0 else 1 end *
case when QuoteNumber is null then 0 else 1 end *
case when ClientNumber is null then 0 else 1 end *
case when ServiceLine is null then 0 else 1 end *
case when ServiceLineCode is null then 0 else 1 end *
case when GroupLeader is null then 0 else 1 end *
case when CreatedBy is null then 0 else 1 end *
case when PTWCompletionDate is null then 0 else 1 end *
case when BudgetedHours is null then 0 else 1 end *
case when BudgetDollars is null then 0 else 1 end *
case when InternalDeadlineDate is null then 0 else 1 end *
case when ProjectDescription is null then 0 else 1 end *
case when Sales is null then 0 else 1 end *
case when Coop is null then 0 else 1 end *
case when PassThrough is null then 0 else 1 end *
case when POStatus is null then 0 else 1 end *
case when PONumber is null then 0 else 1 end as bit
)
as Flag
from t
now, that code works, but it's a bit lengthy, i was wondering if anyone knew of a better way to do this. please note that there are several data types being checked.
further details:
this code is in a view that is being looked at in an application for processing change orders. before a change order can be processed it must meet some data quality checks. this view shows if any of the required data is null.
Just add them up since NULL + "something" is always NULL ...
CREATE TABLE #test(column1 int,column2 varchar(4),column3 float)
INSERT #test VALUES(2,'2',2)
INSERT #test VALUES(0,'1',0)
INSERT #test VALUES(null,'1',0)
INSERT #test VALUES(1,null,0)
INSERT #test VALUES(0,'1',null)
INSERT #test VALUES(null,null,null)
SELECT CASE
WHEN column1 + column2 + column3 is NULL THEN 0 ELSE 1 END, *
FROM #test
from a post I created over 3 years ago ...
Keep in mind that if you have characters that are not numbers that you have to convert to varchar ...
INSERT #test VALUES(0,'abc',null)
Here is the conversion, no need to convert the varchar columns
SELECT CASE WHEN CONVERT(VARCHAR(100),column1)
+ column2
+CONVERT(VARCHAR(100),column3) is NULL THEN 0 ELSE 1 END,*
FROM #test
I think I might go with this solution unless someone comes up with a better one, inspired by #Alireza:
cast(
case when (ChangeOrderNumber is null or
a.ClientName is null or
a.QuoteNumber is null or
ClientNumber is null or
ServiceLine is null or
ServiceLineCode is null or
GroupLeader is null or
CreatedBy is null or
PTWCompletionDate is null or
BudgetedHours is null or
BudgetDollars is null or
InternalDeadlineDate is null or
ProjectDescription is null or
Sales is null or
Coop is null or
PassThrough is null or
POStatus is null or
PONumber is null) then 'false' else 'true'
end as bit) as Flag
Please use IIF() (need to be sql server 2012 or later) I really recommend:
IIF(column1 is null, '0', '1')
What about this one?
select not(a is null or b is null or ...)
You could invert the logic.
SELECT
CASE WHEN ChangeOrderNumber IS NOT NULL
AND ClientName IS NOT NULL
AND QuoteNumber IS NOT NULL
....
THEN 1
ELSE 0
END [Flag]
FROM t
Create a HasValue function that takes in a sql_variant and returns a bit. Then use bitwise AND in your SELECT clause.
CREATE FUNCTION dbo.HasValue(#value sql_variant) RETURNS bit
AS
BEGIN
RETURN (SELECT COUNT(#value))
END
GO
SELECT dbo.HasValue(ChangeOrderNumber)
& dbo.HasValue(ClientName)
& dbo.HasValue(QuoteNumber)
...
as [Flag]
FROM t
Or this:
declare #test1 char(1)
declare #test2 char(1)
declare #outbit bit
set #test1 = NULL
set #test2 = 'some value'
set #outbit = 'True'
select #test1
select #test2
If #test1 + #test2 IS NULL set #outbit = 'False'
Select #outbit
Much simpler -- just use the COALESCE function, which returns the value in the first non-null column.
SELECT Flag = CASE
WHEN COALESCE (column1, column2, column3, ...) IS NULL THEN 0
ELSE 1
END
FROM MyTable