SQL Computer Column Formula - sql

A SQL Table (Trades) has three fields AvgProfit, MinProfit and Hold - Hold is a Computed Colum...
If AvgProfit < MinProfit, Hold = 'Hold' and if AvgProfit > MinProfit, Hold = 'Trade'
The Computed Col formula for Hold is as follows.
SQL Table Trades
AvgProfit varchar(35)
MinProfit varchar(35)
Hold varchar(35)
(case when CONVERT([decimal](8,4),isnull([AvgProfit],(0)),(0))>=CONVERT([decimal](8,4),isnull([MinProfit],(0)),(0)) then 'Trade' else 'Hold' end)
PROBLEM: Updates cause the AvgProfit to be empty at times and this results in an error when the table references the Hold formula
'Error Converting varchar to numeric'
How do I add IS NULL or EMPTY to the above formula, the ISNULL does not catch AvgProfit = '' ??

Consider typing your database with decimal or numeric columns as paxdiablo has suggested. Is there a reason why those columns are set as varchar?
Alternatively if you have to keep your varchar columns, try ISNUMERIC(), http://msdn.microsoft.com/en-us/library/ms186272.aspx. It works with all common SQL numeric types. So you query might become:
ISNUMERIC can be used like this:
select case when ISNUMERIC('123') = 1 then 1 else 0 end ' returns 1
select case when ISNUMERIC('xyz') = 1 then 1 else 0 end ' returns 0
select case when ISNUMERIC(null) = 1 then 1 else 0 end ' returns 0
So your query might become:
case when isnumeric(AvgProfit) = 1 THEN case([AvgProfit] as decimal) else 0 END
Or something similar.

varchar columns should be used for VARiable sized CHARacter columns, not for numeric data.
In other words, they shouldn't be empty (other than NULL, of course, but you've taken care of that).
If you cannot fix that little oversight for some reason, you can make your queries even more complex and slower :-) by doing something like:
select case when xyz = '' then 0 when isnull(xyz) then 0 else xyz end ...
In other words, check for both NULL and empty varchar values.
Myself,I'd fix the schema since it'll be better for you in the long term. I'm merely offering the other solution on the chance that you're not able to do that.

Related

String data right truncation DB2 error

I am receiving the error "String data right truncation" on db2 when I use this query
SELECT BILL_NUMBER, 'PAPERWORK BUT NOT COMPLETE', 'NONE', NULL, '00000',NULL,NULL,TOTAL_CHARGES, NULL FROM TLORDER WHERE
CURRENT_STATUS NOT IN ('COMPLETE','APPRVD','PAPERWISE','BILLD','EDIBILLED','CANCL') AND BILL_TO_CODE NOT LIKE CASE WHEN :INCLUDE_DED = 'No' THEN 'ROCD%' ELSE '1234kkh5656' END
AND EXISTS (SELECT 1 FROM LIST_CHECKIN_AUDIT A WHERE A.BILL_NUMBER = TLORDER.BILL_NUMBER FETCH FIRST 1 ROW ONLY)
AND SITE_ID = :SITE AND DELIVER_BY_END >= CURRENT TIMESTAMP - 3 MONTHS AND COALESCE(PICK_UP_DRIVER,'') = '' AND '00000' =:DRIVER_ID
However when I suppress this line I do not get the error.
AND BILL_TO_CODE NOT LIKE CASE WHEN :INCLUDE_DED = 'No' THEN 'ROCD%' ELSE '1234kkh5656' END
Thanks in advance!
I'd venture to guess that this happens when the value of the :INCLUDE_DED host variable exceeds 2 bytes in length. You do not supply the variable data type, so the query compiler derives it from the right side of the comparison, where the literal 'No' has the length of 2 bytes. If you then assign a value like 'Yes' to the host variable it has to be truncated.
Consider adding an explicit type information to the host variable reference, e.g.:
...WHEN CAST(:INCLUDE_DED AS VARCHAR(10)) = 'No'...
Use the data type appropriate for the range of possible values.
I would first check the datatype of the bill_to_code. You are returning '1234kkh5656' that may exceed the length of the datatype.

SQL: If field is empty, return empty string, otherwise cast as number

I'm running SQL Server 2008 (otherwise I would use Try_Parse) and I need to cast a field as a number in cases where it is non-empty. If the field is empty, an empty string or NULL should be returned. I would prefer if the field was stored as a number in the database, but I have no control over that at this time.
Here is what I have tried:
SELECT CASE WHEN AccountNumber='' THEN '' ELSE CAST(AccountNumber AS bigint) END AS AccountNumber FROM Accounts
OR
SELECT CASE WHEN CAST(AccountNumber AS bigint)=0 THEN '' ELSE CAST(AccountNumber AS bigint) END AS AccountNumber FROM Accounts
But both of these bring back 0 for empty account numbers. I feel that this should be possible but I am going crazy trying to figure it out! Thanks!
You can't select both numbers and empty strings into the same column, because they are incompatible types. That's why the empty strings get converted automatically to 0. NULL should work, however.
SELECT CASE WHEN AccountNumber='' OR AccountNumber IS NULL THEN NULL
ELSE CAST(AccountNumber AS bigint) END AS AccountNumber
FROM Accounts
You can use ISNUMERIC function:
SELECT CASE WHEN ISNUMERIC(AccountNumber) = 1 THEN CAST(AccountNumber AS BIGINT) ELSE NULL END
FROM Accounts

SQL Server : ignore strings in SUM function

I do a sum function over a column. But the column can have string values also. I want SQL Server to ignore the string values and sum only the string values.
Eg: column can have values like 16000Euro or 2588, or 3671.
The input is from user and I cant change validation in the app to integer
I have tried this but still shows error:
SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1
THEN Summe
ELSE 0
END) AS total_Euro
So how can I ignore the string values when doing sum operation?
The error I get is:
Error converting nvarchar value '2588. 'in the int data type.
EDIT: I want SQL to ignore such string values and sum what it can.. The main aim is that Query should not throw any error
Try the below Query, it will work perfectly :)
SELECT SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe + '.0e0') = 1
THEN Summe
ELSE 0
END) AS total_Euro FROM TableName
IsNumeric returns 1 if the varchar value can be converted to ANY number type (includes int, bigint, decimal, numeric, real & float) Values like 1e4,1., 2.0 will create the issue if the above check to bypass these values is not added.
You should not name column same as a keyword in SQL Server , if this cannot be avoided you can escape column name by enclosing in square bracketes [Sum] as shown below
SELECT SUM(CASE WHEN Type = 202 AND ISNUMERIC([Sum]) = 1 THEN [Sum] ELSE 0 END) AS total_Euro
Try this
SUM(CASE WHEN Type = 202 AND case when Sum not like '%[^0-9]%' THEN Sum END ELSE 0 END) AS total_Euro
or
SUM(CASE WHEN Type = 202 AND ISNUMERIC(Sum+'.e0') = 1 THEN Sum ELSE 0 END) AS total_Euro
Try this:
SUM (CASE
WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1 THEN CAST(summe AS DECIMAL(9,2))
ELSE 0 END) AS TotalEuro
I don't know if you do this SUM for one column or what, but also you can filter out what you need and then sum:
SELECT SUM(Summe) AS total_Euro
FROM someTable
WHERE Type_New = 202 AND ISNUMERIC(Summe) = 1
ISNUMERIC function considers strings that contain large numeric (e.g., 9223372036854775808), decimals (e.g., 12.4), currency figures (e.g., $123), and floating-point values (e.g., 1E2) to be strings that can be converted to a numeric data type.
Now to calculate Sum you will have to convert string to an integer[ this assumption is based on
sample data you have posted] but fact is string can be numeric but might not be convertible to an integer; the ISNUMERIC function is limited in the sense that it can tell you only whether the string can be converted to any numeric data type.
So if your column doesn't have string data like 1E3 or 12.4 or $123 which are numeric but not integers you can simply cast the target column to int as below and calculate the sum :
select SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1
THEN CAST(Summe AS INT)
ELSE 0
END) AS total_Euro
FROM test
else you shoudl go for a more generic function which as discussed here..
http://sqlmag.com/t-sql/can-i-convert-string-integer

Why does the number 0 evaluate to a blank space

This is something that has baffled me before but I have never found an explanation for it. I have a column in a SQL Server 2008 database that is of type smallint. I want to look for any rows where the value is NULL or blank, so I say this:
SELECT *
FROM products
WHERE warranty_dom IS NULL
OR warranty_dom = ''
This returns rows with a value of 0
So why is 0 treated as the equivalent of '' ?
0 is not treated as '' per se. Instead, '' is implicitly cast to an integer, and that cast makes it 0.
Try it yourself:
SELECT CAST(0 AS varchar) -- Output: '0'
SELECT CAST('' AS smallint) -- Output: 0
Also, as mentioned elsewhere: If warranty_dom is of type smallint, then it's not possible for it to be blank in the first place.

Nested Logic in Persisted Columns Formula

I'm new to and having trouble with Formulae Syntax in Persisted Columns.
A - I need case when (CustomerAccountID IS NULL and MissCustNameMatched=0) OR errLicensingProgMissing=1 OR errLicensingSubMissing=1 then (1) else (0) end
This won't validate correctly.
B - Or can I do it somehow like this *
case
when [MissCustName] IS true then
when [CustomerAccountName] IS NULL then
(1)
else
(0)
end
else
(0)
end*
Your two cases don't match on column names but following persisted field declaration shows how it could be done using a CASE statement.
CREATE TABLE dbo.Test (
CustomerAccountID INTEGER
, MissCustNameMatched INTEGER
, errLicensingProgMissing INTEGER
, errLicensingSubMissing INTEGER
, persistedField AS
CASE MissCustNameMatched WHEN 1
THEN
CASE CustomerAccountID WHEN 1
THEN 1
ELSE 0
END
ELSE 0
END PERSISTED
)