SQL Server : Computed Column DATEDIFF Clause - sql

What I'm trying to do is the following: I have 3 columns (Control_OpenDate, Control_Record Age, Control_Stage2). Once the row is inserted it will populate Control_OpenDate (01/27/2013) and Control_RecordAge (computed column, see formula).
(datediff(day, [Control_OpenDate], getdate()))
which gives the days up to date.
Everything is working perfect but I want to add like an IF condition to the computed column whenever the column Control_Stage2 is populated if not, do not calculate or add a text...
How can I add the WHERE-statement in the above formula??
Note: I'm entering such formula directly into the column properties, I know there are queries that can do this but is there a way to do it trough a formula.

This can be done using a CASE-statement, as shown here.
Your logic will then look like:
(CASE
WHEN [Control_Stage2] IS NULL THEN NULL -- or -1 or what you like
ELSE datediff(day,[Control_OpenDate],getdate())
END)

This can also be written as a ternary statement (IIF)
IIF ( boolean_expression, true_value, false_value )
IIF is a shorthand way for writing a CASE expression. It evaluates the Boolean expression passed as the first argument, and then returns either of the other two arguments based on the result of the evaluation. That is, the true_value is returned if the Boolean expression is true, and the false_value is returned if the Boolean expression is false or unknown
E.G.
iif([Control_Stage2] is null, null, datediff(day,[Control_OpenDate],getdate()))

Related

How to use statemnts in as criteria in ms access

I have a table and a query to find specific rows from the table. The table contains a column called DueDate which contains a date as a short text. In some cases due date is not applicable so for some situations it contains the string "N/A". What I want to do is the use the expression Expr1:
DateDiff("m";CDate([DueDate]);Date()) in a where statement with a criteria <1. But for the NA fields it gives errors. How can I handle this. Is it possible to use iif statements in criteria.
You can use IIf expressions in a WHERE clause, but I suggest you consider this Switch expression instead. It returns False when DueDate = 'N/A', True when the DateDiff expression returns a value less than 1 month, and Null otherwise.
WHERE Switch
(
DueDate = 'N/A', False,
DateDiff('m',CDate([DueDate]),Date()) < 1, True
) = True
Filter those record with
where DueDate <> 'N/A'

how can I replace blank value with zero in MS-Acess

I have below query in Ms-Access but I want to replace Blank value with zero but I can't get proper answer. Is there any way to replace blank value in zero.
(SELECT
SUM(IIF(Review.TotalPrincipalPayments,0,Review.TotalPrincipalPayments))+
SUM(IIF(Review.TotalInterestPayments,0,Review.TotalInterestPayments ))
FROM
tblReviewScalars as Review
INNER JOIN tblReportVectors AS Report ON(Review.LoanID=Report.LoanID)
WHERE Report.AP_Indicator="A" AND Report.CashFlowDate=#6/5/2011# AND Review.AsofDate=#6/5/2011# AND ( Review.CreditRating =ReviewMain.CreditRating)) AS [Cash Collected During the Period],
I assume TotalPrincipalPayments and TotalInterestPayments are both numeric types, hence the 'blanks' in question is the NULL value.
In SQL, the set function SUM will disregard NULL values, unless all values resolve to NULL in which case NULL is returned (erroneously and the error is with SQL not Access for a change :)
To use a simple example, SELECT SUM(a) FROM T; will only return NULL when a IS NULL is TRUE for all rows of T or when T is empty. Therefore, you can move the 'replace NULL with zero' logic outside of the SUM() function. Noting that "NULLs propagate" in calculations, you will need to handle NULL for each SUM().
You haven't posted the whole of your query e.g. the source of the correlation name ('table alias') ReviewMain is not showm. But it seems clear you are constructing a derived table named "Cash Collected During the Period", in which case your calculated column needs an AS clause ('column alias') such as TotalPayments e.g.
...
(
SELECT IIF(SUM(Review.TotalPrincipalPayments) IS NULL, 0, SUM(Review.TotalPrincipalPayments))
+ IIF(SUM(Review.TotalInterestPayments) IS NULL, 0, SUM(Review.TotalInterestPayments))
AS TotalPayments
FROM tblReviewScalars as Review
INNER JOIN tblReportVectors AS Report
ON Review.LoanID = Report.LoanID
WHERE Report.AP_Indicator = 'A'
AND Report.CashFlowDate = #2011-05-06#
AND Review.AsofDate = #2011-05-06#
AND Review.CreditRating = ReviewMain.CreditRating
) AS [Cash Collected During the Period], ...
An alternative to #onedaywhen's answer is to use the nz function, which is specifically for null-substitution:
SELECT
SUM(NZ(Review.TotalPrincipalPayments,0))+
SUM(NZ(Review.TotalInterestPayments,0))
...
As onedaywhen pointed out, this is functionally equivalent to putting the function outside the aggregate, which may perform better (the function is called once, rather than once per un-aggregated row):
SELECT
NZ(SUM(Review.TotalPrincipalPayments),0)+
NZ(SUM(Review.TotalInterestPayments),0)
...
To change a null value to a zero in an Access 2010 database, open your table, go to design view, click on the field and set the default value to: =0.

Is it possible to have try/catch type updates in SQLite?

UPDATE Table SET Value = 5 WHERE DateTime = '03:42:34';
Sometimes that DateTime will not exist, though. I'm wondering if there's any way that I can have it dynamically attempt then
UPDATE Table SET Value = 5 WHERE DateTime = '03:42:35';
This is probably not possible, especially since 'DateTime` is a string, but wondered if there might be some way of doing it.
I had thought of taking the first 7 characters of the DateTime and having that match, but that's probably not quite precise enough.
The CASE expression sounds like it could do what you want.
A CASE expression serves a role
similar to IF-THEN-ELSE in other
programming languages.
The optional expression that occurs in
between the CASE keyword and the first
WHEN keyword is called the "base"
expression. There are two basic forms
of the CASE expression: those with a
base expression and those without.
In a CASE without a base expression,
each WHEN expression is evaluated and
the result treated as a boolean,
starting with the leftmost and
continuing to the right. The result of
the CASE expression is the evaluation
of the THEN expression that
corresponds to the first WHEN
expression that evaluates to true. Or,
if none of the WHEN expressions
evaluate to true, the result of
evaluating the ELSE expression, if
any. If there is no ELSE expression
and none of the WHEN expressions are
true, then the overall result is NULL.
http://www.sqlite.org/lang_expr.html
Is this what you want?
UPDATE Table
SET Value = 5
WHERE DateTime =
( SELECT MIN(DateTime)
FROM Table
WHERE DateTime >= '03:42:34'
)
;
I got this working in a straightforward way I feel silly for not thinking of originally:
UPDATE Table SET Value = 5 WHERE DateTime BETWEEN datetime('2020-03-21 03:42:35', '-1 second') and datetime('2020-03-21 03:42:35', '+1 second')

What does this SQL Query mean?

I have the following SQL query:
select AuditStatusId
from dbo.ABC_AuditStatus
where coalesce(AuditFrequency, 0) <> 0
I'm struggling a bit to understand it. It looks pretty simple, and I know what the coalesce operator does (more or less), but dont' seem to get the MEANING.
Without knowing anymore information except the query above, what do you think it means?
select AuditStatusId
from dbo.ABC_AuditStatus
where AuditFrequency <> 0 and AuditFrequency is not null
Note that the use of Coalesce means that it will not be possible to use an index properly to satisfy this query.
COALESCE is the ANSI standard function to deal with NULL values, by returning the first non-NULL value based on the comma delimited list. This:
WHERE COALESCE(AuditFrequency, 0) != 0
..means that if the AuditFrequency column is NULL, convert the value to be zero instead. Otherwise, the AuditFrequency value is returned.
Since the comparison is to not return rows where the AuditFrequency column value is zero, rows where AuditFrequency is NULL will also be ignored by the query.
It looks like it's designed to detect a null AuditFrequency as zero and thus hide those rows.
From what I can see, it checks for fields that aren't 0 or null.
I think it is more accurately described by this:
select AuditStatusId
from dbo.ABC_AuditStatus
where (AuditFrequency IS NOT NULL AND AuditFrequency != 0) OR 0 != 0
I'll admit the last part will never do anything and maybe i'm just being pedantic but to me this more accurately describes your query.
The idea is that it is desireable to express a single search condition using a single expression but it's merely style, a question of taste:
One expression:
WHERE age = COALESCE(#parameter_value, age);
Two expressions:
WHERE (
age = #parameter_value
OR
#parameter_value IS NULL
);
Here's another example:
One expression:
WHERE age BETWEEN 18 AND 65;
Two expressions
WHERE (
age >= 18
AND
age <= 65
);
Personally, I have a strong personal perference for single expressions and find them easier to read... if I am familiar with the pattern used ;) Whether they perform differently is another matter...

Matching BIT to DATETIME in CASE statement

I'm attempting to create a T-SQL case statement to filter a query based on whether a field is NULL or if it contains a value. It would be simple if you could assign NULL or NOT NULL as the result of a case but that doesn't appear possible.
Here's the psuedocode:
WHERE DateColumn = CASE #BitInput
WHEN 0 THEN (all null dates)
WHEN 1 THEN (any non-null date)
WHEN NULL THEN (return all rows)
From my understanding, the WHEN 0 condition can be achieved by not providing a WHEN condition at all (to return a NULL value).
The WHEN 1 condition seems like it could use a wildcard character but I'm getting an error regarding type conversion. Assigning the column to itself fixes this.
I have no idea what to do for the WHEN NULL condition. My internal logic seems to think assigning the column to itself should solve this but it does not as stated above.
I have recreated this using dynamic SQL but for various reasons I'd prefer to have it created in the native code.
I'd appreciate any input. Thanks.
The CASE expression (as OMG Ponies said) is mixing and matching datatypes (as you spotted), in addition you can not compare to NULL using = or WHEN.
WHERE
(#BitInput = 0 AND DateColumn IS NULL)
OR
(#BitInput = 1 AND DateColumn IS NOT NULL)
OR
#BitInput IS NULL
You could probably write it using CASE but what you want is an OR really.
You can also use IF..ELSE or UNION ALL to separate the 3 cases