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

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')

Related

Oracle CASE missing right parenthesis for a "in" limit

I have a QRY im developing in Oracle for spotfire. In the where statement, I have a decision case statement and if its True, im trying to pass a list of items to match a column, below is what I have, but its throwing a missing right parenthesis error and I cannot determine why. In short, when a variable is determined True (in this case 9>8 for the example, I need it to result those items, else, result the entire column with no limits.
Note: This works fine when its only 1 item being passed, i.e. 'BOB' but as soon as its multiple, this error occurs.
and Column1 = (CASE When 9>8 Then ('BOB','TOM') Else Column1 END)
Case expressions are best avoided in the where clause. Instead, write the logic with AND and OR:
And (
(9>8 AND Column1 IN ('BOB','TOM'))
OR 9<=8 -- You say you check a variable here, don't forget to check for NULL
)
Oracle does not have a boolean type for use in SQL queries.
Instead, just use basic logic:
and ( (9 > 8 and Column1 in ('BOB','TOM')) or
9 <= 8
)

SQL Server : Computed Column DATEDIFF Clause

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()))

SQL CASE in Query - Odd behavior

Using a Case Statement in a query seems to work fine as long as the only case you want to match to is a string. But if you want to put ">" greater than (date or number), etc, SSMS automatically adds apostrophes around your statement (below) as if it were a string.
How can I get it to accept "greater than date" or "greater than number", etc??
There are two types of CASE expression:
The simple CASE expression compares an expression to a set of simple expressions to determine the result.
The searched CASE expression evaluates a set of Boolean expressions to determine the result.
You want a searched CASE expression. This means that the WHEN should come immediately after the CASE keyword.
CASE WHEN SoldDate <= SubjectDate THEN ...
There are two types of CASE expressions (from msdn):
A Simple CASE compares the specified expression for EQUIVALENCY ONLY
SELECT FieldName CASE WHEN 'Blah' THEN 'Foo' ELSE 'Bah' END
A Searched CASE can do inequalities too but has more verbose syntax:
SELECT CASE WHEN FieldName >= 'Blah' THEN 'Foo' ELSE 'Bah' END
You are trying to use the Simple syntax and need to use the Searched syntax by explicitly writing out the fieldname and comparison for each evaluation.
Your CASE statement syntax is incorrect. WHEN should come directly after CASE
This:
CASE SoldDate WHEN ...
Should be this:
CASE WHEN SoldDate <= SubjectDate THEN SoldFor ELSE EstSalePrice END
Additional Information
Take a look at the MSDN docs for additional examples of CASE syntax.

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