SQL - Setting a variable equal to ISNULL? - tsql

I'm confused by a line of code.
IF #StatusCode = '71'
BEGIN
SET #VarA = Isnull(#VarC, #VarD)
What exactly will be the result for VarA in both the situation VarC is null and is not?

These two codes are equivalent
SET #VarA = Isnull(#VarC, #VarD)
and
if #VarC is not null
set #VarA = #VarC
else
set #VarA = #VarD

ISNUL is an alternative for setting values which are null to the altermative value as in your case Isnull(#VarC, #VarD) if #VarC is null then value will be #var_d else #VarC itself

ISNULL() function lets you return an alternative value when an expression is NULL.
if #VARC is not null, #VarA = #VARC.
If #VARC is null, #VarA = #VarD.

Related

Postgresql update column when passed condition

Is it possible, and if so, how can the following change be achieved?
Given the table:
param_tab
param_id serial
value integer
anothervalue integer
update_date TIMESTAMP
I would like to do something similar to this:
UPDATE param_tab pt
CASE WHEN CONDITION THEN pt.value = 14, pt.anothervalue = 20 END
pt.update_date = someTimestamp;
So update_date is always updated and value and anothervalue only in case of some condition
Use the CASE statement in the correct place:
UPDATE param_tab pt
SET value = CASE WHEN condition THEN 14 ELSE pt.value END,
anothervalue = CASE WHEN condition THEN 20 ELSE pt.anothervalue END,
update_date = someTimestamp;

Where clause check parameter value return a field is NULL

I have a where clause like this:
Where m.Date_6 = Case When #IsCurrentRequest = 1 Then NULL Else m.Date_6 End
#IsCurrentRequest is a bit parameter. I want to check if #IsCurrentRequest = 1 then return m.Date_6 is NULL otherwise return 1. I know this won't work because m.Date_6 = NULL is not working. How do I fix? thanks!
I am not sure I understood correctly your question, but may be this condition is what you are looking for (without using CASE)?
WHERE #isCurrentRequest=1 AND m.date_6 IS NULL OR #isCurrentRequest=0
Anyway, when checking if a value is NULL, you can't use column_name=NULL, but you should use column_name IS NULL (as NULL is a "particular" value)
The = operator will return NULL if any of its operands is NULL, therefore your code will not work as intended.
Try something like this:
WHERE IIF( #IsCurrentRequest = 1, IIF( m.Date_6 IS NULL, 1, 0 ), 1)

T-SQL 'AND' keyword not short-circuiting it seems

The below stored proc works fine except for the fact that when I uncomment the second part of the date check in the 'where' clause it blows up on a date conversion even if the passed in keyword is null or '111'.
I'm open to any suggestions on how to do this dynamic where clause differently.
I appreciate any help.
ALTER PROCEDURE [SurveyEngine].[GetPageOf_CommentsOverviewRowModel]
#sortColumn varchar(50),
#isASC bit,
#keyword varchar(50)
AS
BEGIN
declare #keywordType varchar(4)
set #keywordType = null
if ISDATE(#keyword) = 1
set #keywordType = 'date'
else if ISNUMERIC(#keyword) = 1
set #keywordType = 'int'
select c.CommentBatch BatchID, c.CreatedDate DateReturned, COUNT(c.CommentID) TotalComments
from SurveyEngine.Comment c
where (#keywordType is null)
or (#keywordType = 'date') --and c.CreatedDate = #keyword)
or (#keywordType = 'int' and (CONVERT(varchar(10), c.CommentBatch) like #keyword+'%'))
group by c.CommentBatch, c.CreatedDate
order by case when #sortColumn = 'BatchID' and #isASC = 0 then c.CommentBatch end desc,
case when #sortColumn = 'BatchID' and #isASC = 1 then c.CommentBatch end,
case when #sortColumn = 'DateReturned' and #isASC = 0 then c.CreatedDate end desc,
case when #sortColumn = 'DateReturned' and #isASC = 1 then c.CreatedDate end,
case when #sortColumn = 'TotalComments' and #isASC = 0 then COUNT(c.CommentID) end desc,
case when #sortColumn = 'TotalComments' and #isASC = 1 then COUNT(c.CommentID) end
END
EDIT Sorry, brain cloud. Things need to be initialized differently.
Change the setup to:
declare #keywordType varchar(4)
declare #TargetDate as DateTime = NULL
set #keywordType = null
if ISDATE(#keyword) = 1
begin
set #keywordType = 'date'
set #TargetDate = Cast( #keyword as DateTime )
end
else if ISNUMERIC(#keyword) = 1
set #keywordType = 'int'
Then change:
and c.CreatedDate = #keyword
to:
and c.CreatedDate = Coalesce( #TargetDate, c.CreatedDate )
That will result in a NOP if you are not searching by date.
Based on this guy's blog: http://blogs.msdn.com/b/bartd/archive/2011/03/03/don-t-depend-on-expression-short-circuiting-in-t-sql-not-even-with-case.aspx it looks like you can't guarantee the order of operations in the where clause, even though short circuiting is supported. The execution plan may choose to evaluate the second statement first.
He recommends using a case structure instead (like pst mentioned before) as it is "more" gauranteed. But I don't think I can rewrite your where clause as a case because you're using three different operators (is null, =, and LIKE).

adding conditional statement inside UPDATE

The query:
UPDATE empPac
SET quantityLimit = allocation,
allocationStart = '"&allocationStart&"',
nextUpdate = DATEADD(mm, allocationMonths, "&allocationStart&"),
lastUpdate = GETDATE(),
quantityIssued = 0,
quantityShipped = 0
WHERE allocation IS NOT NULL AND
allocationMonths <> 0 AND
(nextUpdate <= DATEADD(mm, "&checkCondition&", GETDATE()) OR
nextUpdate IS NULL) AND
empIdent in (select empIdent
from employee
where custIdent='"&custIdent&"')
What I want to do is add a conditional statement to the SET quantityLimit = allocation so that rather than having the WHERE allocation IS NOT NULL, I want it to have a conditional statement such as SET quantityLimit = ((allocation IS NULL) ? 0 : allocation)
You can use ISNULL():
SET quantityLimit = ISNULL(allocation, 0)
Equivalent functions for other databases are NVL() for Oracle and IFNULL() for MySQL and SQLite
What you really should be using though is COALESCE() if you want to increase the portability of your code. COALESCE is part of the SQL-92 standard and widely supported across RDBMSes.
What database do you use?
For example, in oracle sql you can write case when allocation is null then 0 else allocation end or nvl (allocation, 0) or coalesce (allocation, 0)
And case syntax in MSSQL is the same as in Oracle.
This is the TSQL (MSSQL) way:
SET quantityLimit = isnull(allocation,0)
Alternatives...
SET quantityLimit = CASE WHEN allocation is null THEN 0 ELSE allocation END
--This one might be handy if you wanted to check for more than just null values. Such as:
----...CASE WHEN allocation is null THEN 0 WHEN some_other_value THEN 1 WHEN ... THEN ... ELSE allocation END
SET quantityLimit = coalesce(allocation,0)
--This one gives you the first non-null value it finds, given a list of places to look. Such as:
----...coalesce(allocation,some_other_field,some_nuther_field,...,0)

Setting a variable in T-SQL from a Query

So I have this query:
select ens_use_new_models_bit from cfo_transaction
inner join dbo.cfo_trans_entity_rel on te_tr_transaction_id=tr_transaction_id
inner join cfo_tran_quote on tq_tr_transaction_id = tr_transaction_id
left outer join cfo_engine_sponsor on ens_rs_sponsor_id = te_co_re_entity_id
where te_rv_rel_type_id=713 and tq_tran_quote_id = 3
It returns a bit value, which can also be NULL. I hardcoded 3 for testing but in reality another proc passes this value in, but that's not important here.
Now, in a stored proc, I need to set a variable that's declared in the proc:
SET #vRtn = NULL
as the string - either 'VBEngines' or 'WFModels', or keep it NULL if the bit from above returns NULL.
'VBEngines' if the bit is off, 'WFModels' if the bit is on.
Then after that, I need to perform a T-SQL condition on the value, to see if it's NULL or not. How would I do this? I'm so bad with SQL.
Thanks.
Assuming that you don't need the bit value itself stored in a variable as that was just a means to an end then this should do it.
select #vRtn = case ens_use_new_models_bit
when 0 then 'VBEngines'
when 1 then 'WFModels'
end /*Implicit Else NULL case*/
from cfo_transaction ...
In the case 0 rows are returned no assignment is made so #vRtn keeps its initial value,
declare #newmodelsbit bit, #vRtn varchar(10)
select #newmodelsbit = ens_use_new_models_bit from cfo_transaction
inner join dbo.cfo_trans_entity_rel on te_tr_transaction_id=tr_transaction_id
inner join cfo_tran_quote on tq_tr_transaction_id = tr_transaction_id
left outer join cfo_engine_sponsor on ens_rs_sponsor_id = te_co_re_entity_id
where te_rv_rel_type_id=713 and tq_tran_quote_id = 3
if #newmodelsbit is null
begin
set #vRtn = null
end
else
begin
if #newmodelsbit = 1 --bit is on
begin
set #vRtn = 'WFModels'
end
else -- bit is off
begin
set #vRtn = ' VBEngines'
end
end