I have an equation that multiplies loads of variables together, if one of those variables is 0 then I don't want it included in the equation by substituting it for 1 which won't affect the result.
A case when - then, statement for each variable validating if they're greater than 0is a bit clunky.
Is there a similar function like IsNull where if the variable is 0 then it returns an alternate value?
--edit #Backs answer is right but apparently after sql 2012 iif was taken out, when i try to write the statement there is a syntax error at the '=' sign. Is there a replacement for iif after sql-2012?
IIF(#variable = 0, 1, #variable)
Related
I have the following code and I am getting an error:
Divide by zero error encountered.
SELECT
CASE WHEN SUM([monthly_qty]) = 0 THEN 999
ELSE ROUND(SUM([monthly_buy] * ([monthly_markup]+100)/100),2) * SUM([monthly_qty] / [monthly_qty]) END as [monthly_total]
FROM [xxxxx].[dbo].[quote_items] WHERE docid='10152'
The field that is causing the error is the second [monthly_qty], just before the END of the CASE statement.
SUM([monthly_qty] / **[monthly_qty]**)
The value of monthly_qty is zero, so the error makes sense, but I am confused as this field is inside the CASE statement, so the expected result is 999
Any help greatly appreciated.
I can't understand reason of some parts of your code like this:
SUM([monthly_qty] / [monthly_qty])
The result is error when [monthly_qty] = Zero, And 1 for non zero.
Anyway, You can set a default value When "monthly_qty" is zero:
IIF([monthly_qty]= 0,'YOUR_DEFAULT_VALUE', [monthly_qty] / [monthly_qty])
Then:
SUM(IIF([monthly_qty]= 0,'YOUR_DEFAULT_VALUE', [monthly_qty] / [monthly_qty]))
Have a read at MS Docs, there is an example of your case under Remarks.
The CASE expression evaluates its conditions sequentially and stops
with the first condition whose condition is satisfied. In some
situations, an expression is evaluated before a CASE expression
receives the results of the expression as its input. Errors in
evaluating these expressions are possible. Aggregate expressions that
appear in WHEN arguments to a CASE expression are evaluated first,
then provided to the CASE expression. For example, the following query
produces a divide by zero error when producing the value of the MAX
aggregate. This occurs prior to evaluating the CASE expression.
The reason is simple. This code:
SUM([monthly_qty]) = 0
Does not prevent a divide-by-zero in this code:
SUM([monthly_qty] / [monthly_qty])
The expressions are different.
The simplest solution (and essentially the "standard" approach) is to use NULLIF():
SUM([monthly_qty] / NULLIF([monthly_qty], 0))
However, I wonder if you really intend:
SUM([monthly_qty]) / NULLIF(SUM([monthly_qty]), 0)
I tried executing the following SQL statement.
SELECT CASE WHEN CHARINDEX('~','test.pdf') > 0
THEN SUBSTRING('test.pdf',CHARINDEX('~', 'test.pdf'), -10)
ELSE NULL
END
This resulted in an error 'Invalid length parameter passed to the substring function.'. However, this was not expected because it is not going to execute anyway.
This query is a simplified version of my requirement. Actually we are computing the value length for the substring. The real scenario is also given below :
SELECT CASE
WHEN CHARINDEX('~', 'test.pdf') > 0 THEN SUBSTRING('test.pdf', CHARINDEX('~', 'test.pdf') + 1, CHARINDEX('~', 'test.pdf', (CHARINDEX('~', 'test.pdf', 1)) + 1) - CHARINDEX('~', 'test.pdf') - 1)
ELSE NULL
END;
In the example its hardcoded as 'test.pdf' but in real scenario it would be values like '111111~22222~33333~4444.pdf' from Table column. Also, I'm not sure this file name should always follow this format. Hence, a validation is required.
Actually, the computation for length is quite expensive, and don't want to use it twice in this query.
You have passed -10 as a constant to substring(). This function does not allow negative values for the third argument:
length
Is a positive integer or bigint expression that specifies how many characters of the expression will be returned. If length is negative, an error is generated and the statement is terminated. If the sum of start and length is greater than the number of characters in expression, the whole value expression beginning at start is returned.
SQL Server catches this problem during the compile phase. This has nothing to do with CASE expression evaluation, but with parsing the expressions.
how can I convert to T-Sql this one?
IIf([ESSValue]<>0,Int([ESSValue]*100),"")
I think the following pretty much does what you want:
select coalesce(cast(EssValue * 100 as int), 0)
Here is the thinking. The comparison to zero is unimportant, because 0 times any value is going to be zero. The iif() returns an integer (I think) because the "then" argument is an integer; the empty string gets converted to zero.
I'm not 100% certain about the last statements with regard to MS Access, but that is how iif() works in SQL Server.
I should add. Although I don't approve of iif() for conditional expressions (because case is the standard and more powerful), SQL Server does support it. So you could write:
IIf([ESSValue]<>0, cast([ESSValue]*100 as int), '')
Note: As I mentioned earlier, the '' will be converted to 0.
CASE WHEN ESSValue <> 0
THEN CAST(ESSValue * 100 AS INT)
ELSE NULL
END as fieldname
For case expression the default is NULL if doesn't meet any condition, so you dont really need the ELSE condition
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...
Are there any nvl() equivalent functions in SQL?
Or something close enough to be used in the same way in certain scenarios?
UPDATE:
no if statementsno case statementsno isnullno coalesce
select nvl (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581;
(expression)
SODIUFOSDIUFSDOIFUDSF
1 row(s) retrieved.
select isnull (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581;
674: Routine (isnull) can not be resolved.
Error in line 1
Near character position 8
select coalesce (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581;
674: Routine (coalesce) can not be resolved.
Error in line 1
Near character position 8
select decode(purge_date, NULL, "01/01/2009", purge_date) from id_rec where id=74115;
800: Corresponding types must be compatible in CASE expression.
Error in line 1
Near character position 57
ISNULL (for a single replace)
or
COALESCE (Returns the first nonnull expression among its arguments.)
SQL Server:
IsNull or COALESCE
http://msdn.microsoft.com/en-us/library/ms184325.aspx
Sybase:
isnull function
http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.blocks/html/blocks/blocks162.htm
Postgres:
I couldn't find one though haven't fully checked. Suggests to select where IS NULL and build from here
http://archives.postgresql.org/pgsql-sql/1998-06/msg00142.php
DB2 - COALESCE
http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0000780.htm
You seem to be using Informix.
AFAIK, there is DECODE there:
DECODE(field, NULL, 'it is null, man', field) should give you same result as NVL(field, 'it is null, man')
Please post exact name and version of the RDBMS you are using.
The problem with your DECODE statement that is generating the 800 error is simple. '01/01/2009' is being treated as a string, and it's actually the 4th argument that generates the error.
Appreciate that the input and output of a DECODE statement can be different data-types, so the engine requires you to be more explicit in this case. (Do you want purge_date cast as a string or the string '01/01/2009', or the string argument parsed as a date or the original date? There's no way for the engine to know.
Try this:
SELECT DECODE(purge_date, NULL, '01/01/2009'::DATE, purge_date)
You could also write that 3rd argument as:
DATE('01/01/2009')
MDY(1,1,2009)
depending on version and personal preference.