473,387 Members | 1,687 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Sorting mixed type fields...

I have a field in my database which stores product codes. This field
is a varchar. Some users use characters in their codes but most just
use numbers. Whenever I go to sort the products by code the order of
the numbers go something like: 1, 100, 101, 2, 210, 220, 2500, 3, ...
I understand why this is sorted this way but is there anyway I can
have it sort the numbers in their proper numeric order (1,2,3,100,
....) and just have them always appear before any codes that contain
characters? Right now I just have users put zeros in front of their
numbers like: 0001, 0100, 0101, 0002, ...
Jul 20 '05 #1
4 5210
Ray,

CREATE TABLE foo (c1 varchar(10));
INSERT INTO foo VALUES ('1');
INSERT INTO foo VALUES ('2');
INSERT INTO foo VALUES ('13');
INSERT INTO foo VALUES ('1X');

SELECT *
FROM foo
ORDER BY RIGHT('0000000000'+c1,10);

Hope that helps,
Rich
"Ray Lavelle" <bo************@yahoo.com> wrote in message
news:d8**************************@posting.google.c om...
I have a field in my database which stores product codes. This field
is a varchar. Some users use characters in their codes but most just
use numbers. Whenever I go to sort the products by code the order of
the numbers go something like: 1, 100, 101, 2, 210, 220, 2500, 3, ...
I understand why this is sorted this way but is there anyway I can
have it sort the numbers in their proper numeric order (1,2,3,100,
...) and just have them always appear before any codes that contain
characters? Right now I just have users put zeros in front of their
numbers like: 0001, 0100, 0101, 0002, ...

Jul 20 '05 #2
Do you care how the strings containing alphas are sorted? If not, you could
do something like this:

create table foo (col1 char(5))
go
insert foo values ('x')
insert foo values ('01')
insert foo values ('ax')
insert foo values ('2')
insert foo values ('0034')
insert foo values ('034')
insert foo values ('03')

select col1
from foo
order by
case when col1 like '%[a-z]%' then 99999
else convert(int, col1)
end

If you care how the alphas are ordered, too, I think you'll want to create a
function that handles zero-extending anyhthing convertible to numerics and
returns a char(x) type. You 'order by' on your function output. This
seemed to work for me (algorithm is ugly but it did the job):

create function orderit (@a_col char(5)) returns char(5)
as
begin
declare @num_scrap int
declare @char_scrap char(5)
declare @temp_len int
if (@a_col like '%[a-z]')
begin
set @char_scrap = @a_col
end
else
begin
set @num_scrap = convert(int,@a_col)
set @char_scrap = convert(char(5),@num_scrap)
set @temp_len = datalength(rtrim(@char_scrap))
set @char_scrap = replicate('0',5-@temp_len)+rtrim(@char_scrap)
end
return (@char_scrap)
end
go

select col1,
<mydb>.dbo.orderit(col1)
from foo
order by <mydb>.dbo.orderit(col1)

"Ray Lavelle" <bo************@yahoo.com> wrote in message
news:d8**************************@posting.google.c om...
I have a field in my database which stores product codes. This field
is a varchar. Some users use characters in their codes but most just
use numbers. Whenever I go to sort the products by code the order of
the numbers go something like: 1, 100, 101, 2, 210, 220, 2500, 3, ...
I understand why this is sorted this way but is there anyway I can
have it sort the numbers in their proper numeric order (1,2,3,100,
...) and just have them always appear before any codes that contain
characters? Right now I just have users put zeros in front of their
numbers like: 0001, 0100, 0101, 0002, ...

Jul 20 '05 #3
>> I have a field [sic] in my database which stores product codes.
This field [sic] is a varchar. <<

That is the root of your problem; you don't know that a column is not
a field (row is not a record, table is not a file), so you did not
bother to define the domain and put a CHECK() constraint to enforce
the rules for these codes. Using VARCHAR(n) is also a mistake for
encoding schemes 95% of the time -- it messes up checking, printing
forms, etc.
Right now I just have users put zeros in front of their numbers

like: 0001, 0100, 0101, 0002, ... <<

I don't know why you cannot use GTIN, EAN, UPC or some other industry
standard code. It sounds like the "database designer" did no research
or planning; can you fix your system and fire him?

And, yes, that padding is what you have to do and you'd better enforce
it in the DDL, not in every query that has been and ever shall be
written against the Database. Start by cleaning up the entire
database.

Based on the specs I have to invent myself since you did not give any,
your table should have a column something like this:

CREATE TABLE Products
(product_code CHAR(10) NOT NULL PRIMARY KEY
CHECK (product_code LIKE '[0-9][0-9][0-9][0-9][A-Z][A-Z]'),
...);

The Regular expression extension in SQL Server is a bit weaker than
the SIMILAR TO predicate in SQL-92, but it is quite usable.
Jul 20 '05 #4
This worked perfect, thanks!

"Rich Dillon" <ri********@no.spam> wrote in message news:<gL***************@newsread4.news.pas.earthli nk.net>...
Ray,

CREATE TABLE foo (c1 varchar(10));
INSERT INTO foo VALUES ('1');
INSERT INTO foo VALUES ('2');
INSERT INTO foo VALUES ('13');
INSERT INTO foo VALUES ('1X');

SELECT *
FROM foo
ORDER BY RIGHT('0000000000'+c1,10);

Hope that helps,
Rich
"Ray Lavelle" <bo************@yahoo.com> wrote in message
news:d8**************************@posting.google.c om...
I have a field in my database which stores product codes. This field
is a varchar. Some users use characters in their codes but most just
use numbers. Whenever I go to sort the products by code the order of
the numbers go something like: 1, 100, 101, 2, 210, 220, 2500, 3, ...
I understand why this is sorted this way but is there anyway I can
have it sort the numbers in their proper numeric order (1,2,3,100,
...) and just have them always appear before any codes that contain
characters? Right now I just have users put zeros in front of their
numbers like: 0001, 0100, 0101, 0002, ...

Jul 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Paul Kirby | last post by:
Hello All I am trying to update me code to use arrays to store a group of information and I have come up with a problem sorting the multiple array :( Array trying to sort: (7 arrays put into...
7
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) ...
8
by: Mike MacSween | last post by:
tblCourses one to many to tblEvents. A course may have an intro workshop (a type of event), a mid course workshop, a final exam. Or any combination. Or something different in the future. At...
3
by: alex_peri | last post by:
Hello All, I am having problems with sorting a recordset by fields in Access. I have a table with three columns called ID, SNo and Time and would like to sort the records by Time. I would like to...
8
by: Bern McCarty | last post by:
Is it at all possible to leverage mixed-mode assemblies from AppDomains other than the default AppDomain? Is there any means at all of doing this? Mixed-mode is incredibly convenient, but if I...
8
by: Edward Diener | last post by:
By reuse, I mean a function in an assembly which is called in another assembly. By a mixed-mode function I mean a function whose signature has one or more CLR types and one or more non-CLR...
1
by: LoopyNZ | last post by:
Hi there, I have an IIF expression that is returning a 0 (exact match), 1 (partial match), or 2 (no match) based on comparing text fields (see below). However, when I try to sort the results...
1
KevinADC
by: KevinADC | last post by:
Introduction In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar...
3
KevinADC
by: KevinADC | last post by:
If you are entirely unfamiliar with using Perl to sort data, read the "Sorting Data with Perl - Part One and Two" articles before reading this article. Beginning Perl coders may find this article...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.