String data right truncation DB2 error - sql

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.

Related

How to use Decode Function in the case where column has string values

I have a view xxabc_v (shown below), I need to update the "Code" column to Null wherever it is N/A when "Value" column sum (900+(-900)=0) becomes zero for the "field_name" values (Demand A+Demand B) for the "Date" 01-Apr-21.
How can I put the decode logic to code column in the above case?
Table structure and expected output:
You don't want decode() because a much simpler method works:
select nullif(code, 'N/A')
This returns NULL when code takes on the specified value.
If you actually want to change the data, then you want update:
update t
set code = NULL
where code = 'N/A';
EDIT:
I see, you have an extra condition. So, use case:
(case when code = 'N/A' and
sum(value) over (partition by id, date) = 0
then NULL
else code
end)
I assumed that you need date wise id wise sum when to sum(). Please check this out:
select date,id,(case when sum(value)over(partition by date,id)=0 and code='N/A' then NULL
else Code end)code, field_name,value
from tablename

Error in SQL case statement when trying to create binary flag?

Here's my query where I'm testing my case structure:
SELECT TOP 1 CASE 130
WHEN '000000000000000' THEN '0'
WHEN '' THEN '0'
WHEN 'XXX' THEN '0'
WHEN 'RETIRED' THEN '0'
WHEN 'STUDENT' THEN '0'
ELSE '1'
END AS employed_flag
INTO #employedbeta
FROM CreditBureau.Experian
I'm just trying to make a new temporary table, but I'd like my case to work first. I keep getting the error:
Conversion failed when converting the varchar value 'XXX' to data type int.
In the database, the column 130 is a char, and I don't know why it thinks I want to make it a number. SQL server management studio, if it matters.
The column name is 130, I left the '1' off because I rewrote it here but I get the error regardless in my actual query.
130 is an integer literal. If that's really the column name, you'll have to escape it using double quotes. As a side note, you should probably return the same type (char) in the else branch too:
CASE "130"
WHEN '000000000000000' THEN '0'
WHEN '' THEN '0'
WHEN 'XXX' THEN '0'
WHEN 'RETIRED' THEN '0'
WHEN 'STUDENT' THEN '0'
ELSE '1'
END AS employed_flag
130 is a really bad column name. But, I would simplify the logic to:
SELECT TOP 1 (CASE WHEN [130] IN ('000000000000000', '', 'XXX', 'RETIRED', 'STUDENT')
THEN 0 ELSE 1
END) AS employed_flag
INTO #employedbeta
FROM CreditBureau.Experian;
Note that I also changed the employed_flag to a numeric value rather than a string. That makes more sense to me.

SQL - Error converting date and/or time from character string

I have a datetime column which I'm checking for null. All I want to do is have it say "No Next Appointment" if the column is null. However I'm getting an error:
conversion failed when converting date and/or time from character string
I'm not sure why. I tried a couple different ways to write the query but it keeps giving me the same error.
Here is my query-
SELECT
t1.PatientID,
t1.FullName,
t1.CurrentRAF_DW,
t1.NumberOfCompletedClinicVisits,
t1.PreferredServiceLocation,
case when t1.IsVip = 1 then 'Yes' else 'No' end as [IsVip],
case when t1.PatientTier = 'Critical' then 'Every Three Weeks'
when t1.PatientTier = 'Serious' then 'Every 1 Month'
when t1.PatientTier = 'Fair' then 'Every 2 Months'
when t1.PatientTier = 'Good' then 'Every 3 Months'
else ' '
end as [Cadence],
t1.PatientTier,
t2.hcc_18,
t2.hcc_19,
t2.hcc_21,
t2.hcc_22,
t2.hcc_12,
t2.hcc_136,
t2.hcc_137,
t2.hcc_108,
t2.hcc_88,
t2.hcc_111,
t2.hcc_85,
t2.hcc_55,
t1.LastCompletedClinicVisit,
case when t1.NextScheduledClinicVisit is not null then t1.NextScheduledClinicVisit else 'No Next Appointment' end as [NextScheduledVisit]
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
ON t1.PatientID = t2.emr_id
The column in question here is "NextScheduledClinicVisit".
First, you should use coalesce(). Second, the types should match:
coalesce(convert(varchar(255), t1.NextScheduledClinicVisit ),
'No Next Appointment'
) as [NextScheduledVisit]
If NextScheduledClinicVisit is a sting, then you probably want to use an appropriate conversion specification (such as 121) or use format().
The column will sometimes contain a datetime field and sometimes a string.
Try casting the datetime to a varchar.
I'd go about solving your issue using the following method.
Wrap the error generating column in a try_convert and review some sample records
If above successful write your case statement using a "case when [col] is null then 'formatted text 1' ..." type statement and review some sample records
Apparently Gordon's answer is working so use that, but I might look into try_Convert for future reference.

Conversion failed when converting the nvarchar value 'These are comments for errors' to data type int

I have been struggling to get this corrected for a while now. Below is the part of a query where I am getting the error in the MAX function and I am not able to understand why its trying to convert to data type INT. I would like to keep it as string as this particular column is for comments
MAX(CASE
WHEN ID = -416 AND Value IS NOT NULL
THEN Value
ELSE 'No Error'
END) AS Error_Comments
This particular table is still in test and hence for test purposes there is only one comment added for now which is
These are comments for errors
I also tried converting the case statement but it still gives the same error:
MAX(CONVERT(VARCHAR, CASE
WHEN ID = -416 AND Value IS NOT NULL
THEN Value
ELSE 'No Error'
END)) AS Error_Comments
I also tried this but didn't work: Value <> ''
I couldn't find the answer in any of the stackoverflow questions.
Try this:
declare #t table(ID int, value nvarchar(1000))
insert #t values(-416, 'These are comments for errors'),
(-416, null)
SELECT
COALESCE(MAX(CASE WHEN ID = -416 THEN value END), 'No Error') AS Error_Comments
FROM #t
Result:
These are comments for errors
It would seem that value is an integer. So, your case statement is returning different types, and SQL Server has decided that the type should be an integer. Your string doesn't convert.
So, do an explicit conversion:
MAX(CASE WHEN ID = -416 AND Value IS NOT NULL THEN cast(Value as varchar(255))
ELSE 'No Error'
END) AS Error_Comments
EDIT:
The comment makes a lot of sense. I suppose this should be:
COALESCE(CAST(CASE WHEN ID = -416 AND Value IS NOT NULL THEN VALUE END) as varchar(255)),
'No Error'
)

SQL Computer Column Formula

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.