Error select from sqlserver - 2008 - sql-server-2008

I have a problem with date conversion and the displayed error. I think the block below is the problem.
I need to bring the difference between the dates and calculate them to know if the invoice is open "A" or downloaded "B", but it is returning the error below.
Conversion failed when converting the varchar value '30/12/' to datatype int.
<pre><code>
SELECT [vl_recebido]
,[vl_pago]
,[vl_original]
,s.[dt_baixa]
,[dt_vencto]
,[dt_rp]
,S.[id_divisao]
,[nro_baixa]
,S.[nm_cliente]
,ISNULL(C.id_cliente, -1) AS id_cliente
,[nro_documento]
,[ds_moeda]
,[cd_cc]
,[cd_t_cta]
,[cd_port]
,[cd_oper]
,[ds_observacao]
,[ds_complemento]
,[nm_resp_baixa]
,[qtd_recibo]
,[qtd_pagto]
,t.[qtd_colaborador]
,t.[vl_meta]
,[flag]
,[bco_sacado]
,[cheque_numero]
,[in_processo]
,isnull(af.id_aging_fatura, 5) as id_aging_fatura
,af.dsc_faixa_aging
,af.qtd_aging
,datediff(d, s.dt_vencto, s.dt_baixa) as qtd_aging_calc
,case when s.dt_baixa is null then 'A' else 'B' end as status_da_fatura
FROM stg_recibo_baixas S
LEFT JOIN dim_cliente C ON C.cod_cliente = S.cod_cliente
AND C.id_divisao = S.id_divisao
INNER JOIN tab_colaborador_baixa t ON t.id_mes = CONVERT(INT, CONVERT(VARCHAR(6), s.dt_baixa, 112))
left join dim_aging_faturas af on af.qtd_aging = (select min(qtd_aging) from dim_aging_faturas a
where a.qtd_aging >= case when datediff(d, s.dt_vencto, case when s.dt_baixa is null then getdate() else convert(datetime, substring(s.dt_baixa, 8, 4) + '-' + substring(s.dt_baixa, 4, 2) +'-'+ substring(s.dt_baixa, 0, 2), 103) end) < 0 then 0 else datediff(d, s.dt_vencto, convert(datetime, substring(s.dt_baixa, 8, 4) + '-' + substring(s.dt_baixa, 4, 2) +'-'+ substring(s.dt_baixa, 0, 2), 103)) end)
</code></pre>

Related

Mysql order by sorting not working as expected descending

i am facing a a very strange behavior regarding mysql orderby sort, I am trying to sort the records by fee_range high to low which is being computed in run time first 3,4 rows have lowest values and then order by takes effect and and further all records are sorted as expected is there any thing that i am missing?
here is the query that i am running
SELECT `ddd`.`ID`, CONCAT(ddd.title, " ", ddd.name) AS name, `ddd`.`url`, `ddd`.`doc_gender`, `ddd`.`edu_degrees`, TRIM(BOTH ", " FROM ddd.specializations) AS specializations, `ddd`.`tel_appointments`, CONCAT("https://s3-eu-west-1.amazonaws.com/mdpk/images/profile-pics/doctors/", ddd.profile_image) AS profile_image, `ddd`.`yearsofexperience`, IF(MIN(IF(daas.fee > 0, `daas`.`fee`, NULL)) = MAX(IF(daas.fee > 0, `daas`.`fee`, NULL)), MIN(IF(daas.fee > 0, `daas`.`fee`, NULL)), CONCAT(MIN(IF(daas.fee > 0, `daas`.`fee`, NULL)), "-", MAX(IF(daas.fee > 0, `daas`.`fee`, NULL)))) AS fee_range, `dhdtl`.`locality`, `dhdtl`.`city`, `ddd`.`star_rating`, `ddd`.`is_paying`, `ddd`.`divert_to_cc`, `ddd`.`patient_records`, IF(MAX(daas.allow_online_booking + daas.has_active_subs) = 2, 1, 0) AS is_bookable, MAX(daas.has_active_subs) AS has_active_subscription, `ddd`.`verified_patients`, `ddd`.`average_wait_time`, (ddd.positive_reviews + ddd.negative_reviews) AS total_reviews, IF(ddd.verified_patients > 0 AND
ddd.positive_reviews + ddd.negative_reviews > 0 AND
ddd.positive_reviews + ddd.negative_reviews > 0 AND
(ddd.is_paying = 1 OR 1 = 0), ROUND(ddd.positive_reviews * 100 / (ddd.positive_reviews + ddd.negative_reviews), 0), 0) AS recommendation_percentage
FROM `doc_doc_details` AS `ddd`
JOIN `doc_specialization_relation` `dsr` ON `dsr`.`user_id` = `ddd`.`ID`
JOIN `doc_hosp_doctor` `dhd` ON `ddd`.`ID` = `dhd`.`user_id`
JOIN `doc_app_adv_settings` `daas` ON `dhd`.`hospital_id` = `daas`.`subs_id` AND `daas`.`prov_id`=`ddd`.`ID`
JOIN `doc_hospital_details` `dhdtl` ON `dhd`.`hospital_id` = `dhdtl`.`hosp_detail_id`
WHERE `dhdtl`.`country_id` = 1
AND `dhdtl`.`city_id` = '1'
AND `dsr`.`specialization_id` IN('72')
AND `ddd`.`published` = 1
GROUP BY `ddd`.`ID`
ORDER BY `has_active_subscription` DESC, MAX(fee_range) DESC, `ddd`.`manual_web_rank`, `ddd`.`computed_web_rank`, `dhd`.`is_primary` DESC
LIMIT 20
here are the results
any help regarding this issue would be really appreciated
The CONCAT-function inside the fee_range-column turns the column into a character column (causing ordering by alphabetical order) and you are ordering the column with MAX(fee_range) whereas it should be just fee_range.

How to auto increment a string with sql query

I am stuck at a point where i have to increment a string, and my strings are of type C001,SC001,B001
in my data base they are defined like
what i am trying to do do is write a query which check the previous highest code present into my db and the incriment it to +1
for example C001 -> C002,C009->C010,C099`->C100 and so on
Similarly for SC001->SC002,SC009->SC010,SC099->SC100 and so on
Similarly fro B001 -> B002,B009->B010,B099`->B100 and so on
I have a query which my friend has suggested me to use but that query only incriminating AAAA->AAAA01 , AAAA09->AAAA10
query is
SELECT id AS PrevID, CONCAT(
SUBSTRING(id, 1, 4),
IF(CAST(SUBSTRING(id, 5) AS UNSIGNED) <= 9, '0', ''),
CAST(SUBSTRING(id, 5) AS UNSIGNED) + 1
) AS NextID
FROM (
-- since you allow strings such as AAAA20 and AAAA100 you can no longer use MAX
SELECT id
FROM t
ORDER BY SUBSTRING(id, 1, 4) DESC, CAST(SUBSTRING(id, 5) AS UNSIGNED) DESC
LIMIT 1
) x
when i am replacing ID with CategoryCode it is giving me PrevID-C004 NextID-C00401 which is not my requirement i want PrevID-C004 and NextID->C005
NOTE i am using my sqlServer 5.1
Just try this one ,
SELECT
CategoryCode,CAST(CONCAT(LPAD(CategoryCode,1,0),LPAD(MAX(RIGHT(CategoryCode,
3)) + 1, 3, 0) ) AS CHAR),
FROM test
SELECT
SubCategoryCode,CAST(CONCAT(LPAD(SubCategoryCode,2,0),
LPAD(MAX(RIGHT(CategoryCode, 3)) + 1, 3, 0) ) AS CHAR),
FROM test
SELECT
BrandCode,CAST(CONCAT(LPAD(BrandCode,1,0), LPAD(MAX(RIGHT(BrandCode, 3)) +
1, 3, 0)) AS CHAR) FROM test

How do I loop through a stored procedure within a sql statement

I know this sounds like an old question, but I haven't been able to solve my problem even after reading endless answers, so I'll try to be specific.
I have a table with a column of text, which sometimes includes HTML tags. I need to remove MOST of the HTML but leave some. I've written the following code which will do that:
DECLARE #Start INT = 1;
DECLARE #End INT = 1;
DECLARE #Length INT = 0;
DECLARE #Keep INT = 0;
DECLARE #ReplaceChar VARCHAR(10) = '';
DECLARE #Offset INT = 0;
RETURN;
WHILE #Start > 0 AND #End > 0
BEGIN
SET #ReplaceChar = (SELECT CASE WHEN SUBSTRING(#HTMLText,#Start + 1, 7) IN ('/strike')
THEN ('</strike>')
WHEN SUBSTRING(#HTMLText,#Start + 1, 6) IN ('strike')
THEN ('<strike>')
WHEN SUBSTRING(#HTMLText,#Start + 1, 4) IN ('br /')
THEN ('<br />')
WHEN SUBSTRING(#HTMLText,#Start + 1, 3) IN ('/th', '/tr','/td','th ')
THEN ('<' + SUBSTRING(#HTMLText,#Start + 1, 3) + '>')
WHEN SUBSTRING(#HTMLText,#Start + 1, 2) IN ('th', 'tr', 'td')
THEN ('<' + SUBSTRING(#HTMLText,#Start + 1, 2) + '>')
WHEN SUBSTRING(#HTMLText,#Start + 1, 2) IN ('/p', '/i', '/b')
THEN ('<' + SUBSTRING(#HTMLText,#Start + 1, 2) + '>')
WHEN SUBSTRING(#HTMLText,#Start + 1, 1) IN ('p', 'i', 'b')
THEN ('<' + SUBSTRING(#HTMLText,#Start + 1, 1) + '>')
ELSE ''
END);
SET #Keep = (SELECT CASE WHEN SUBSTRING(#HTMLText,#Start + 1, 7) IN ('/strike') THEN 1
WHEN SUBSTRING(#HTMLText,#Start + 1, 6) IN ('strike') THEN 1
WHEN SUBSTRING(#HTMLText,#Start + 1, 4) IN ('br /') THEN 1
WHEN SUBSTRING(#HTMLText,#Start + 1, 3) IN ('/th', '/tr', '/td') THEN 1
WHEN SUBSTRING(#HTMLText,#Start + 1, 2) IN ('th', 'tr', 'td') THEN 1
WHEN SUBSTRING(#HTMLText,#Start + 1, 2) IN ('/p', '/i', '/b') THEN 1
WHEN SUBSTRING(#HTMLText,#Start + 1, 1) IN ('p', 'i', 'b') THEN 1
ELSE 0
END);
SET #HTMLText = RTRIM((LTRIM(STUFF(#HTMLText,#Start, #Length,#ReplaceChar))));
SET #Start = CHARINDEX('<', #HTMLText,#Start + #Offset);
SET #End = CHARINDEX('>', #HTMLText,CHARINDEX('<', #HTMLText,#Start + #Offset));
SET #Length = (#End - #Start) + 1;
SET #Offset = #Start + #Keep;
END;
RETURN #HTMLText;
This needs to be applied to the Details column in the following code, after the Replace functions have completed.
DECLARE #Region NVARCHAR(12) = '11'
DECLARE #Location NVARCHAR (1000) = '1932'
DECLARE #IPM NVARCHAR (500) = '1594,1611,1934' -- for 1932 --'8055,15591'--for 1941
DECLARE #NoteFromDate DATETIME = '20150101'
DECLARE #NoteToDate DATETIME= '20160701'
SELECT r.RegionName
, l.LocationName
, CASE WHEN o.CurrentLocationId <> l.LocationId
THEN '*'
ELSE ''
END AS NotCurrentLocation
, e.DisplayName AS IPM
, ec.DisplayName AS Counselor
, oni.OffenderId
, an.LastName + ', ' + an.FirstName + COALESCE(' ' + an.MiddleName,
'') AS OffenderName
, oni.NoteDate
,REPLACE(REPLACE(REPLACE(REPLACE(
ono.Details,'''',''),' ',' '),'&',' & '),'rsquo;','-')
FROM ref.Employee AS e
INNER JOIN ref.Location AS l
ON e.LocationId = l.LocationId
INNER JOIN ref.Region AS r
ON l.RegionId = r.RegionId
INNER JOIN ind.OffenderNoteInfo AS oni
ON e.EmployeeId = oni.StaffId
INNER JOIN ind.Offender AS o
ON oni.OffenderId = o.OffenderId
INNER JOIN ind.OffenderNote AS ono
ON oni.OffenderNoteInfoId = ono.OffenderNoteInfoId
INNER JOIN ind.OffenderNoteInfo_ContactMode AS onicm
ON oni.OffenderNoteInfoId = onicm.OffenderNoteInfoId
INNER JOIN ind.AliasName AS an
ON oni.OffenderId = an.OffenderId AND an.AliasNameTypeId = 0 --Default Name
LEFT JOIN ind.OffenderCurrentFactPart AS ocfp
ON o.OffenderId = ocfp.OffenderId
LEFT JOIN hsn.CounselorAssignment AS ca
ON ocfp.PriCounselorAssignmentId = ca.CounselorAssignmentId
LEFT JOIN ref.Employee AS ec
ON ca.EmployeeId = ec.EmployeeId
WHERE e.LocationId IN (
SELECT Value
FROM vnfa.udf_FnSplit(#Location, ',')) AND e.EmployeeTypeId = 106 --Treatment Program Supervisor
AND oni.NoteTypeId = 11 --Facility Notes
AND onicm.ContactModeId = 229 --Institution Fidelity Review
AND (oni.NoteDate >= #NoteFromDate AND oni.NoteDate <= #NoteToDate) AND e.EmployeeId IN (
SELECT Value
FROM vnfa.udf_FnSplit(#IPM, ','));
How do I get code section 1 to run within code section two?
Input for the Details column might look like:
<p style="margin: 0in 0in 0pt;"><span style="font-family: Calibri;">All areas were reviewed </span></p>
Output should be:
<p>All areas were reviewed</p>
I'm just not seeing a way to combine these two for each row. Thanks for any suggestions.
I would do as others suggest and write this code in another language. You can do it with tsql however. The first code can be a scalar function that can then be applied to the details column in your query.

MySQL Calculations using variables

Why is this not working? I would like to get the result of:
(#sum_hours * #rate_hours) + (#sum_travel * #rate_travel) + (#sum_miles * #rate_miles)
The results of my sub queries are as follows:
#sum_hours = 5.00000, #sum_travel = 2.00000, #sum_miles = 0.00000
#rate_hours = 35.00000, #rate_travel = 35.00000, #rate_miles = NULL
#_rate_hours = CAST(IF(#rate_hours, #rate_hours, 0) AS DECIMAL(10, 5)) = 35.00000
#_rate_travel = CAST(IF(#rate_travel, #rate_travel, 0) AS DECIMAL(10, 5)) = 35.00000
#_rate_miles = CAST(IF(#rate_miles, #rate_miles, 0) AS DECIMAL(10, 5)) = 0.00000
So now that I have some values, I'm doing:
#total:= (#sum_hours * #_rate_hours)
I expect this to be 175, but it returns NULL. If I directly declare #sum_hours as 5
#sum_hours:= 5
I get 175, as expected. Am I doing something wrong? How can I get this to return 175, assuming I don't know that the values are supposed to be 5, 35 and 175?
#sum_hours is being cast as decimal, but with and without the cast it does not work.
Edit:
This is a stripped back version of the query, as the JOINs and subqueries aren't relevant, just the return details. All numeric fields are stored as FLOAT in the database. The values are confirmed in the result, but the calculation for #total does not work (returns null).
I have worked around this using COALESCE and some other bits, but I'm still curious as to why it would not calculate properly - or what I'm doing wrong.
SELECT
#sum_hours:= CAST(hours AS DECIMAL(10, 5)),
#sum_travel:= CAST(travel AS DECIMAL(10, 5)),
#sum_miles:= CAST(miles AS DECIMAL(10, 5)),
#rate_hours:= (SELECT ... returns 35),
#rate_travel:= (SELECT ... returns 35),
#rate_miles:= (SELECT ... returns NULL),
#_rate_hours = CAST(IF(#rate_hours, #rate_hours, 0) AS DECIMAL(10, 5)),
#_rate_travel = CAST(IF(#rate_travel, #rate_travel, 0) AS DECIMAL(10, 5)),
#_rate_miles = CAST(IF(#rate_miles, #rate_miles, 0) AS DECIMAL(10, 5)),
#total:= (#sum_hours * #_rate_hours) + (#sum_travel * #_rate_travel) + (#sum_miles * #_rate_miles)
FROM table
WHERE
id = '...'
GROUP BY id

MySQL - my months are current stored 0-11

I thought I ran into a bug with MySQL 5.1, but the bug was in the perl code that's creating the timestamps. perl's localtime uses 0-11 for months, but MySQL's datetime uses 1-12. So, I've got all these malformed timestamps that I need to update.
2012-00-19 09:03:30
This should be:
2012-01-19 09:03:30
The problem is that the date functions for MySQL return NULL on a 00 month. Is there a way to do this in MySQL?
EDIT: Solution =
UPDATE test_stats
SET start_time = CAST(CONCAT(SUBSTRING(start_time, 1, 5),
CAST((CAST(SUBSTRING(start_time, 6, 2) AS UNSIGNED) + 1) AS CHAR(2)),
SUBSTRING(start_time, 8, 12)) AS DATETIME);
By the way, I was using MySQL 5.1
This should work:
UPDATE MyTable
SET DateTimeField =
CAST (
SUBSTRING(DateTimeString, 1, 5) -- '2012-'
+ CAST((CAST(SUBSTRING(DateTimeString, 6, 2) AS INT) + 1) AS VARCHAR) -- '00' => '1'
+ SUBSTRING(DateTimeString, 8, 12) -- '-19 09:03:30'
AS DATETIME)
Test with this select
DECLARE #x VARCHAR(50) = '2012-00-19 09:03:30'
SELECT CAST(SUBSTRING(#x, 1, 5)
+ CAST((CAST(SUBSTRING(#x, 6, 2) AS INT) + 1) AS VARCHAR)
+ SUBSTRING(#x, 8, 12) AS DATETIME)