Order By alphanumeric values like numeric - tsql

there is a table's fields on MSSQL Serrver 2005 as VARCHAR. It contains alphanumeric values like "A,B,C,D ... 1,2,3,...,10,11,12" etc.
When i use below codes;
....
ORDER BY TableFiledName
Ordering result is as follow 11,12,1,2,3 etc.
When i use codes as below,
....
ORDER BY
CASE WHEN ISNUMERIC(TableFiledName) = 0 THEN CAST(TableFiledNameAS INT) ELSE TableFiledName END
I get error message as below;
Msg 8114, Level 16, State 5, Line 1 Error converting data type varchar
to float.
How can get like this ordering result: 1,2,3,4,5,6,7,8,9,10,11,12 etc..
Thanks in advance.

ISNUMERIC returns 1 when the field is numeric.
So your first problem is that it should be ...
CASE WHEN ISNUMERIC(TableFiledName) = 1 THEN
But this alone won't work.
You need to prefix the values with zeroes and take the rightmost
order by
case when ISNUMERIC(FieldName) =1
then right('000000000'+FieldName, 5)
else FieldName
end
Using 5 allows for numbers up to 99999 - if your numbers are higher, increase that number.
This will put the numbers before the letters. If you want the letters before the numbers, then you can add an isnumeric to the sort order - ie:
order by
isnumeric(FieldName),
case...
This won't cope with decimals, but you haven't mentioned them

Related

Check if character varying is between range of numbers

I hava data in my database and i need to select all data where 1 column number is between 1-100.
Im having problems, because i cant use - between 1 and 100; Because that column is character varying, not integer. But all data are numbers (i cant change it to integer).
Code;
dst_db1.eachRow("Select length_to_fault from diags where length_to_fault between 1 AND 100")
Error - operator does not exist: character varying >= integer
Since your column supposed to contain numeric values but is defined as text (or version of text) there will be times when it does not i.e. You need 2 validations: that the column actually contains numeric data and that it falls into your value restriction. So add the following predicates to your query.
and length_to_fault ~ '^\+?\d+(\.\d*)?$'
and length_to_fault::numeric <# ('[1.0,100.0]')::numrange;
The first builds a regexp that insures the column is a valid floating point value. The second insures the numeric value fall within the specified numeric range. See fiddle.
I understand you cannot change the database, but this looks like a good place for a check constraint esp. if n/a is the only non-numeric are allowed. You may want to talk with your DBA ans see about the following constraint.
alter table diags
add constraint length_to_fault_check
check ( lower(length_to_fault) = 'n/a'
or ( length_to_fault ~ '^\+?\d+(\.\d*)?$'
and length_to_fault::numeric <# ('[1.0,100.0]')::numrange
)
);
Then your query need only check that:
lower(lenth_to_fault) != 'n/a'
The below PostgreSQL query will work
SELECT length_to_fault FROM diags WHERE regexp_replace(length_to_fault, '[\s+]', '', 'g')::numeric BETWEEN 1 AND 100;

Cast to int instead of decimal?

I have field that has up to 9 comma separated values each of which have a string value and a numeric value separated by colon. After parsing them all some of the values between 0 and 1 are being set to an integer rather than a numeric as cast. The problem is obviously related to data type but I am unsure what is causing it or how to fix it. The problem only exists in the case statement, the split_part function seems to be working perfect.
Things I have tried:
nvl(split_part(one,':',2),0) = COALESCE types text and integer cannot be matched
nvl(split_part(one,':',2)::numeric,0) => Invalid input syntax for type numeric
numerous other cast/convert variations
(CASE WHEN split_part(one,':',2) = '' THEN 0::numeric ELSE split_part(one,':',2)::numeric END)::numeric => runs but get int value of 0
When using the split_part function outside of case statement it does work correctly. However, I need the result to be zero for null values.
split_part(one,':',2) => 0.02068278096187390979 (expected result)
When running the code above I get zero but expect 0.02068278096187390979
Field "one" has the following value 'xyz: 0.02068278096187390979' before the split_part function.
EXAMPLE:
create table test(one varchar);
insert into test values('XYZ: 0.50000000000000000000')
select
one ,split_part(one,':',2) as correct_value_for_those_that_are_not_null ,
case
when split_part(one,':',2) = '' then null
else split_part(one,':',2)::numeric
end::numeric as this_one_is_the_problem
from test
However, I need the result to be zero for null values.
Your example does not deal with NULL values at all, though. Only addressing the empty string ('').
To replace either with 0 reliably, efficiently and without casting issues:
SELECT part1, CASE WHEN part2 <> '' THEN part2::numeric ELSE numeric '0' END AS part2
FROM (
SELECT split_part(one, ':', 1) AS part1
, split_part(one, ':', 2) AS part2
FROM test
) sub;
See:
Best way to check for "empty or null value"
Also note that all SQL CASE branches must agree on a common data type. There have been minor adjustments in the logic that determines the resulting type in the past, so the version of Postgres may play a role in corner cases. Don't recall the details now.
nvl()is not a Postgres function. You probably meant COALESCE. The manual:
This SQL-standard function provides capabilities similar to NVL and IFNULL, which are used in some other database systems.

RIGHT Function in UPDATE Statement w/ Integer Field

I am attempting to run a simple UPDATE script on an integer field, whereby the trailing 2 numbers are "kept", and the leading numbers are removed. For example, "0440" would be updated as "40." I can get the desired data in a SELECT statement, such as
SELECT RIGHT(field_name::varchar, 2)
FROM table_name;
However, I run into an error when I try to use this same functionality in an UPDATE script, such as:
UPDATE schema_name.table_name
SET field_name = RIGHT(field_name::varchar, 2);
The error I receive reads:
column . . . is of type integer but expression is of type text . . .
HINT: You will need to rewrite or cast the expression
You're casting the integer to varchar but you're not casting the result back to integer.
UPDATE schema_name.table_name
SET field_name = RIGHT(field_name::TEXT, 2)::INTEGER;
The error is quite straight forward - right returns textual data, which you cannot assign to an integer column. You could, however, explicitly cast it back:
UPDATE schema_name.table_name
SET field_name = RIGHT(field_name::varchar, 2)::int;
1 is a digit (or a number - or a string), '123' is a number (or a string).
Your example 0440 does not make sense for an integer value, since leading (insignificant) 0 are not stored.
Strictly speaking data type integer is no good to store the "trailing 2 numbers" - meaning digits - since 00 and 0 both result in the same integer value 0. But I don't think that's what you meant.
For operating on the numeric value, don't use string functions (which requires casting back and forth. The modulo operator % does what you need, exactly: field_name%100. So:
UPDATE schema_name.table_name
SET field_name = field_name%100
WHERE field_name > 99; -- to avoid empty updates

ORDER BY CASE & Ordinal not working

Sorting column #7 as an example -
This code does not sort data at all:
ORDER BY CASE WHEN '1'='2' THEN 5
WHEN '1'='1' THEN 7
ELSE 13 END
If I change it to a hard-coded ordinal it works:
ORDER BY 7
As long as the respective expressions in the SELECT list are of the same type, you can do it by using the expressions themselves instead of the SELECT list number:
SELECT expression1, expression2, ...
...
ORDER BY CASE
WHEN 1=2
THEN expression5
WHEN 1=1
THEN expression7
ELSE expression13
END;
If the data types are not the same, season with type casts.
Your query does not work because only integer literals can be used as column numbers in ORDER BY. In all other cases, an integer just stands for its constant value.
If it were not like this, ORDER BY expressions could easily become ambiguous. Look at the following:
... ORDER BY intcol + 3;
Should that mean “add three” or “add expression number three from the SELECT list”?

T-sql - The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value. Differences between = and LIKE

I have a query with the below WHERE clauses
WHERE
I.new_outstandingamount = 70
AND ISNUMERIC(SUBSTRING(RA.new_stampernumber,7, 4)) = 1
AND (DATEDIFF(M,T.new_commencementdate, SUBSTRING(RA.new_stampernumber,7, 10)) >= 1)
AND RA.new_applicationstatusname = 'Complete'
AND I.new_feereceived > 0
AND RA.new_stampernumber IS NOT NULL
AND T.new_commencementdate IS NOT NULL
RA.new_stampernumber is a string value which contains three concatenated pieces of information of uniform length. The middle piece of info in this string is a date in the format yyyy-MM-dd.
In order to filter out any rows where the date in this string in not formatted as expected I do a check to see if the first 4 characters are numeric using the ISNUMERIC function.
When I run the query I get an error message saying
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
The line that is causing this error to occur is
AND (DATEDIFF(M,T.new_commencementdate, SUBSTRING(RA.new_stampernumber,7, 10)) >= 1)
When I comment out this line I don't get an error.
What is strange is that if I replace
AND ISNUMERIC(SUBSTRING(RA.new_stampernumber,7, 4)) = 1
with
AND SUBSTRING(RA.new_stampernumber,7, 4) IN ('2003','2004','2005','2006','2007','2008','2009','2010', '2011', '2012','2013','2014','2015'))
the query runs successfully.
Whats even more strange is that if I replace the above working line with this
AND SUBSTRING(RA.new_stampernumber,11, 1) = '-'
I get the error message again. But if I replace the equals sign with a LIKE comparison it works:
AND SUBSTRING(RA.new_stampernumber,11, 1) LIKE '-'
When I remove the DATEDIFF function and compare the results of each of these queries they all return the same resultset so it is not being caused by different data being returned by the different clauses.
Can anyone explain to me what could be causing the out-of-range error to be thrown for some clauses and not for others if the data being returned is in fact the same for each clause?
Thanks,
Neil
Different execution plans.
There is no guarantee that the WHERE clauses are processed in particular order. Presumably when it works it happens to filter out erroring rows before attempting the cast to date.
Also ISNUMERIC itself isn't very reliable for what you want. I'd change the DATEDIFF expression to something like the below
DATEDIFF(M, T.new_commencementdate,
CASE
WHEN RA.new_stampernumber LIKE
'______[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
THEN SUBSTRING(RA.new_stampernumber, 7, 10)
END) >= 1 )