sql - conversion error when changing 'and' to 'or' - sql

I have a database table in sql server 2008. My query is breaking for a reason that is unknown to me:
select release_id, url_id,tt_projectid, release_title, tech_area, current_state, dateadd(ss,last_built,'12/31/1969 20:00:00') as recent_Date,
autobuild_count, manualbuild_count, bcm_build_count, config_count, force_count, transition_only_count,
auto_integ_count,last_auto_integ,dateadd(ss,integ_complete_date,'12/31/1969 20:00:00') as integ_date
from tablename
where (auto_integ_count > 0
and MONTH(last_auto_integ) = '1'
and YEAR(last_auto_integ) = '2013')
and (release_id > 36000)
order by release_id desc
The above query works fine, but when I change the last line of the where close from 'and' to 'or' I get this conversion error:
Conversion failed when converting date and/or time from character string.
I'm puzzled as to why changing
'and (release_id > 36000)'
to
'or (release_id > 36000)'
would cause such an error

The reason is because last_auto_integ is being stored as a string rather than as a date. These lines in the where clause are not being executed with the and -- by happenstance -- because none occur when release_id > 360000.
From what I can see, there are no other places in the query where you might be converting a string to a date format.
You can identify these values using:
select last_auto_integ
from tablename
where isdate(last_auto_integ) = 0 and last_auto_integ is not null
You can fix the problem in the query by using case:
where month(case when isdate(last_auto_integ) = 1 then last_auto_integ end) = 1 and
year(case when isdate(last_auto_integ) = 1 then last_auto_integ end) = 2013
Or, you can just use substring() to extract the month and year from whatever date format you are using.

Because when you change AND to OR you are getting a lot more rows returned, and one of these other expressions is failing:
dateadd(ss,integ_complete_date,'12/31/1969 20:00:00')
MONTH(last_auto_integ)
YEAR(last_auto_integ)

With only AND, it doesn't need to evaluate the other expressions for rows whose release_id is <= 36000, so it's not encountering the strings that are causing the problem on date conversion.

Related

REPLACE to just have a number causing conversion failure

I'm trying to do a count to see how many fields in column value are > 10:
SELECT
COUNT(CASE WHEN t.value > 10)
THEN 1
ELSE NULL
END
FROM table t
WHERE t.DATE = '2017-01-01'
However, the column has a few custom entries like +15 or >14.0, so I added the following:
SELECT
COUNT(CASE WHEN value LIKE '>%'
and Replace(value, '>', '') > 10)
FROM table t
WHERE t.DATE = '2017-01-01'
However, after doing that, I get the following error:
Conversion failed when converting the varchar value '>14.0' to data
type int. Warning: Null value is eliminated by an aggregate or other
SET operation.
Seeing I have no access to rewrite the database with an UPDATE, does anyone have a workaround solution?
You could fix this, either by simply changing 10 to 10.0:
SELECT CASE WHEN '14.0' > 10.0 THEN 1 ELSE 0 END
This will cause the implicit conversion of '14.0' to decimal rather than int, which works, or you explicitly convert it:
SELECT CASE WHEN CONVERT(DECIMAL(14, 2), '14.0') > 10 THEN 1 ELSE 0 END
If it were me however, and I was not in a position to update the data, and do something a bit left field, like use a numeric data type to store numbers, I would ignore these values completely, and simply use TRY_CONVERT to avoid the conversion errors:
SELECT
COUNT(CASE WHEN TRY_CONVERT(DECIMAL(14, 2), value) > 10 THEN 1 END)
It is a varchar column, so the possibilities of what nonsense could be in there are endless, you might get a query that works now by replacing > and +, but then what about when someone puts in <, or ends up with a space in between like + 14, or something completely random like 'aaaa', where does it end?
It would be helpful to see the table and sample data, but it sounds like you have strings that are numbers and a sign.
You can cast it to convert the data since you are mixing and matching data types.
SELECT
COUNT(CASE WHEN CAST(value AS VARCHAR(10)) LIKE '>%'
and CAST(Replace(value, '>', '') AS your_num_datatype_here) > 10)

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.

How can I sort DB2 results based on month and year parameter from separate column

I am using DB2.
I have a query that returns a specific date in the following format: yyyy-mm-dd
SELECT DATE FROM ABC.DTS
Then I have devised another query that is supposed to return results that match the date returned above
SELECT COUNT(*)
FROM ABC.ATY
WHERE ID between 1 and 1000000000
AND MONTH(PRS) = MONTH(from DTS)
AND YEAR(PRS) = YEAR(from DTS)
AND CKPYE = ' '
;
I am getting an error when I run the second query that says: ILLEGAL SYMBOL "MONTH". SOME SYMBOLS THAT MIGHT BE LEGAL ARE: XMLELEMENTXMLPI. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.19.56.
How can I return the results that match the date that is returned from the first query?
Is there another route/strategy I need to instead of the one I am currently trying?
Many thanks in advance.
See if this works for you:
SELECT COUNT(*)
FROM ABC.ATY
JOIN ABC.DTS ON MONTH(PRS) = MONTH(Date) AND YEAR(PRS) = YEAR(DATE)
WHERE ID between 1 and 1000000000
AND CKPYE = ' '
;

Adding text string to CASE Statement

I am using the following SQL CASE:
SELECT
BomMast.BomStockCode
, BomMast.BomDescription
, CASE
WHEN StkItem.AveUCst <= 0 THEN 'ERROR'
WHEN StkItem.AveUCst > 0 THEN (StkItem.AveUCst * BomComp.ProductionQty)
END AS TotalCost
FROM BomComp
INNER JOIN BomMast
ON BomMast.BomID = BomComp.BomMasterKey
INNER JOIN StkItem
ON StkItem.StockLink = BomComp.ComponentStockLink
But I get the following message:
Msg 8114, Level 16, State 5, Line 2
Error converting data type varchar to float.
Am I not allowed to add test within the CASE statement?
Thank you!
Change your query to:
SELECT BomMast.BomStockCode
,BomMast.BomDescription
,CASE
WHEN StkItem.AveUCst <= 0
THEN 'ERROR'
WHEN StkItem.AveUCst > 0
THEN CAST((StkItem.AveUCst * BomComp.ProductionQty) AS NVARCHAR(MAX))
END AS TotalCost
FROM BomComp
INNER JOIN BomMast ON BomMast.BomID = BomComp.BomMasterKey
INNER JOIN StkItem ON StkItem.StockLink = BomComp.ComponentStockLink
The datatypes of the values you want to show in either branches of your CASE statements need to be the same in order to work.
Edit:
After #underscore_d's suggestion, I also consider that it would be a far better option to display NULL instead of the message ERROR and then handle this NULL value in the application level.
Hence, your case statement will change to:
CASE
WHEN StkItem.AveUCst <= 0
THEN NULL
WHEN StkItem.AveUCst > 0
THEN (StkItem.AveUCst * BomComp.ProductionQty)
END AS TotalCost
Yes, text can be used as the result a case statement, as can any datatype, but each case must return the same type, as the results column must have one type only.
Your [TotalCost] column has conflicting data types. [StkItem.AveUCst] is a float and the literal value of 'ERROR' is a varchar. If you are intending to retain the benefits of number-based value in your results column, consider replacing 'ERROR' with the SQL keyword NULL.
Your column TotalCost (neither any other column) can be a type-mixture. In first case it would be a varchar, in second case it would be floator something like that. THAT IS NOT POSSIBLE.

select case statement error in mssql

SELECT top 1
case
when VR = -99999.99
then 0
else cast((VR*1.732) as decimal(38,3))
end
FROM pseb.dbo.datasource
where FeederID=5003
order by datetime desc
The above query is working fine, but I need to return varchar value '--' instead of returning 0
if I do like that
SELECT top 1
case
when VR = -99999.99
then '--'
else cast((VR*1.732) as decimal(38,3))
end
FROM pseb.dbo.datasource
where FeederID=5003
order by datetime desc
means it returns the following error:
Msg 8114, Level 16, State 5, Line 1 Error converting data type varchar
to numeric.
please help me to solve it
The problem is that you are returning two different data types from the same column. The rule with SQL Server that numeric types take precedence over string types, i.e. in a situation like yours a string gets converted to a number, not the other way around.
So to solve this you can cast your number to a string.
One option is to do something like this:
SELECT top 1
case when VR = -99999.99 then '--'
else
cast
(
cast((VR*1.732) as decimal(38,3)
)
as varchar(50))
end
FROM pseb.dbo.datasource where FeederID=5003 order by datetime desc