473,569 Members | 2,691 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sequential Number in an Update

this is a slight change to a fequently asked question around here. I
have a table which contains a "sortorder" column where a user can
specify some arbitrary order for records to be displayed in. Users
have sometimes ordered records the way we used to number lines in a
BASIC program (10,20,30, etc.). I'd like to do an update query and fix
this so that every record is in sequential order. I found an example
in this newsgroup of how to do this.

However, I have a slight problem! Sometimes, the users duplicated the
sortorders. So for example, I might have two records were the
sortorder is 20. The query I found in this newsgroup does not work in
that case. Here is some code so that you can see what I mean.

create table sorttest (
label char(5),
sortorder int
)
go
insert sorttest values ('joe',20)
insert sorttest values ('dan',10)
insert sorttest values ('jim',44)
insert sorttest values ('tom',20)
insert sorttest values ('jan',50)

-- data dump
select label, sortorder from sorttest order by sortorder

-- I'd like to fix all of the sortorder fields so that they are
sequential
update sorttest
set sortorder = (
select count(*)
from sorttest subquery
where sorttest.sortor der <= subquery.sortor der
)

-- note that tom and joe BOTH HAVE SORTORDER = 4
select label, sortorder from sorttest order by sortorder

drop table sorttest
Thanks in advance for any help.

Oct 27 '06 #1
19 4150
You need additional criteria to sort uniquely.
Try this

update sorttest
set sortorder = (
select count(*)
from sorttest subquery
where sorttest.sortor der < subquery.sortor der
or (sorttest.sorto rder = subquery.sortor der
and sorttest.label <= subquery.label)
)

Oct 27 '06 #2
If it is one tine update you can do this . Note values of sortcolumns
in all the rows will be changed

DECLARE @sortcol INT
SET @sortcol = 0 -- You can set to any other value if you like
UPDATE sorttest
SET @sortcol = sorcol = @sortcol + 1

M A Srinivas
er*******@gmail .com wrote:
this is a slight change to a fequently asked question around here. I
have a table which contains a "sortorder" column where a user can
specify some arbitrary order for records to be displayed in. Users
have sometimes ordered records the way we used to number lines in a
BASIC program (10,20,30, etc.). I'd like to do an update query and fix
this so that every record is in sequential order. I found an example
in this newsgroup of how to do this.

However, I have a slight problem! Sometimes, the users duplicated the
sortorders. So for example, I might have two records were the
sortorder is 20. The query I found in this newsgroup does not work in
that case. Here is some code so that you can see what I mean.

create table sorttest (
label char(5),
sortorder int
)
go
insert sorttest values ('joe',20)
insert sorttest values ('dan',10)
insert sorttest values ('jim',44)
insert sorttest values ('tom',20)
insert sorttest values ('jan',50)

-- data dump
select label, sortorder from sorttest order by sortorder

-- I'd like to fix all of the sortorder fields so that they are
sequential
update sorttest
set sortorder = (
select count(*)
from sorttest subquery
where sorttest.sortor der <= subquery.sortor der
)

-- note that tom and joe BOTH HAVE SORTORDER = 4
select label, sortorder from sorttest order by sortorder

drop table sorttest
Thanks in advance for any help.
Oct 27 '06 #3
>have a table which contains a "sortorder" column where a user can specify some arbitrary order for records to be displayed in. <<

The classic error of mixing display and data in the RDBMS?
>Users have sometimes ordered records [sic] the way we used to number lines in a BASIC program (10, 20, 30, etc.). I'd like to do an update query and fix this so that every record [sic] is in sequential order. <<
Rows and records are totally diffreent concepts. You are still
thinking about a file system, not RDBMS. Line numbers are a physical
representation of a paper form or input screen, not a logical data
model element.
>However, I have a slight problem! Sometimes, the users duplicated the sortorders. <<
Gee, do you suppose that might be due to the fact that they are not
relational, have no rules for validation or verifiication? And the
fact that you do not have a UNIQUE constraint on this silly column????
>Thanks in advance for any help. <<
You might want to read book on RDBMS, data modeling and tiered
architectures

Oct 28 '06 #4
er*******@gmail .com wrote:
this is a slight change to a fequently asked question around here. I
have a table which contains a "sortorder" column where a user can
specify some arbitrary order for records to be displayed in. Users
have sometimes ordered records the way we used to number lines in a
BASIC program (10,20,30, etc.). I'd like to do an update query and fix
this so that every record is in sequential order. I found an example
in this newsgroup of how to do this.

However, I have a slight problem! Sometimes, the users duplicated the
sortorders. So for example, I might have two records were the
sortorder is 20. The query I found in this newsgroup does not work in
that case. Here is some code so that you can see what I mean.

create table sorttest (
label char(5),
sortorder int
)
go
insert sorttest values ('joe',20)
insert sorttest values ('dan',10)
insert sorttest values ('jim',44)
insert sorttest values ('tom',20)
insert sorttest values ('jan',50)

-- data dump
select label, sortorder from sorttest order by sortorder

-- I'd like to fix all of the sortorder fields so that they are
sequential
update sorttest
set sortorder = (
select count(*)
from sorttest subquery
where sorttest.sortor der <= subquery.sortor der
)

-- note that tom and joe BOTH HAVE SORTORDER = 4
select label, sortorder from sorttest order by sortorder

drop table sorttest
Thanks in advance for any help.

WITH t AS
(SELECT label, sortorder,
ROW_NUMBER() OVER (ORDER BY sortorder,label ) AS new_order
FROM sorttest)
UPDATE t SET sortorder = new_order;

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Oct 28 '06 #5
--CELKO-- wrote:
>
The classic error of mixing display and data in the RDBMS?
This RDBMS is driving a content management system. The table in
question contains a list of URL links - basically a navigation element
for the website. So obviously, the CMS user has a requirement to put
the links in some arbitrary order that makes sense to them.

Imagine that this was the data that I wanted to have on this navigation
element:

http://google.com
http://apple.com

Pray tell how YOU would store those values so that the resulting HTML
page shows them in the order that the user wants?
fact that you do not have a UNIQUE constraint on this silly column????
If you stop and think about this (but that seems to be a handicap for
you) you will realize that there can't be a UNIQUE constraint on the
sortorder column. If you honestly can't figure out why, ask nicely and
maybe I'll explain it to you.

But I really would love to hear how you would keep a list of links in
an arbitrary order

Oct 28 '06 #6
>there can't be a UNIQUE constraint on the sortorder column.<<

What is the nature of a sort on a set? It is a sequence; every element
has a unique position in that sequence. This is by definition.
>But I really would love to hear how you would keep a list of links in an arbitrary order <<
Now we have some more specs to use.

CREATE TABLE UserLinks
(user_id INTEGER NOT NULL
REFERENCES Users(user_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
preference_nbr INTEGER NOT NULL
CHECK (preference_nbr 0),
content_url VARCHAR (255) NOT NULL
CHECK (content_url LIKE 'http://%.com'), -- or whatever grep() you
need
PRIMARY KEY (user_id, preference_nbr) ); -- here is your unique
constraint

You will need a proc to move them around once they are in the table.

CREATE PROCEDURE SwapUserLinks
(@my_user_id INTEGER, @old_preference _nbr INTEGER, @new_preference _nbr
INTEGER)
AS
UPDATE UserLinks
SET preference_nbr
= CASE preference_nbr
WHEN @old_preference _nbr
THEN @new_preference _nbr
ELSE preference_nbr + SIGN(@old_prefe rence_nbr - @new_pos)
END
WHERE user_id = @my_user_id
AND (preference_nbr BETWEEN @old_preference _nbr AND
@new_preference _nbr
OR preference_nbr BETWEEN @new_preference _nbr AND
@old_preference _nbr);

Play with it a little bit. It takes a starting position in the list
and moves it up or down to the new position and slides the elements in
between either up or down.

When you want to drop a few rows, remember to close the gaps with this
code. It will start the numbering at 1 within each user.

CREATE PROCEDURE CloseUserLinksG aps(@my_user_id INTEGER)
AS
UPDATE UserLinks
SET preference_nbr
= (SELECT COUNT (U1.preference_ nbr)
FROM UserLinks AS U1
WHERE U1.preference_n br <= UserLinks.prefe rence_nbr
AND user_id = @my_user_id
AND @my_user_id = UserLinks.user_ id);

Oct 28 '06 #7
>there can't be a UNIQUE constraint on the sortorder column.<<

What is the nature of a sort on a set? It is a sequence; every element
has a unique position in that sequence. This is by definition.
>But I really would love to hear how you would keep a list of links in an arbitrary order <<
Now we have some more specs to use.

CREATE TABLE UserLinks
(user_id INTEGER NOT NULL
REFERENCES Users(user_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
preference_nbr INTEGER NOT NULL
CHECK (preference_nbr 0),
content_url VARCHAR (255) NOT NULL
CHECK (content_url LIKE 'http://%.com'), -- or whatever grep() you
need
PRIMARY KEY (user_id, preference_nbr) ); -- here is your unique
constraint

You will need a proc to move them around once they are in the table.

CREATE PROCEDURE SwapUserLinks
(@my_user_id INTEGER, @old_preference _nbr INTEGER, @new_preference _nbr
INTEGER)
AS
UPDATE UserLinks
SET preference_nbr
= CASE preference_nbr
WHEN @old_preference _nbr
THEN @new_preference _nbr
ELSE preference_nbr + SIGN(@old_prefe rence_nbr - @new_pos)
END
WHERE user_id = @my_user_id
AND (preference_nbr BETWEEN @old_preference _nbr AND
@new_preference _nbr
OR preference_nbr BETWEEN @new_preference _nbr AND
@old_preference _nbr);

Play with it a little bit. It takes a starting position in the list
and moves it up or down to the new position and slides the elements in
between either up or down.

When you want to drop a few rows, remember to close the gaps with this
code. It will start the numbering at 1 within each user.

CREATE PROCEDURE CloseUserLinksG aps(@my_user_id INTEGER)
AS
UPDATE UserLinks
SET preference_nbr
= (SELECT COUNT (U1.preference_ nbr)
FROM UserLinks AS U1
WHERE U1.preference_n br <= UserLinks.prefe rence_nbr
AND user_id = @my_user_id
AND @my_user_id = UserLinks.user_ id);

Oct 28 '06 #8
CHECK (content_url LIKE 'http://%.com'), -- or whatever grep() you

Interesting, I would really like to know how you would validate this as a
URL (or email address) in a constraint.

You need to look for a lot more that http:// and .com; there is http / https
for a start, ftp: there is .com, .co.uk, .net and about 2 dozen other
domains and there is sub-domains to handle.....

The only way you are going to write a safe constraint like this is to use
regular expressions and for that you'll need CLR.

So, come on celko - just how would you write this contraint to truely
validate the url is valid and also protect yourself from a DBA making an
accidental update (or melicious....)? ?????

--
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jc*******@eart hlink.netwrote in message
news:11******** **************@ e64g2000cwd.goo glegroups.com.. .
>>there can't be a UNIQUE constraint on the sortorder column.<<

What is the nature of a sort on a set? It is a sequence; every element
has a unique position in that sequence. This is by definition.
>>But I really would love to hear how you would keep a list of links in an
arbitrary order <<

Now we have some more specs to use.

CREATE TABLE UserLinks
(user_id INTEGER NOT NULL
REFERENCES Users(user_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
preference_nbr INTEGER NOT NULL
CHECK (preference_nbr 0),
content_url VARCHAR (255) NOT NULL
CHECK (content_url LIKE 'http://%.com'), -- or whatever grep() you
need
PRIMARY KEY (user_id, preference_nbr) ); -- here is your unique
constraint

You will need a proc to move them around once they are in the table.

CREATE PROCEDURE SwapUserLinks
(@my_user_id INTEGER, @old_preference _nbr INTEGER, @new_preference _nbr
INTEGER)
AS
UPDATE UserLinks
SET preference_nbr
= CASE preference_nbr
WHEN @old_preference _nbr
THEN @new_preference _nbr
ELSE preference_nbr + SIGN(@old_prefe rence_nbr - @new_pos)
END
WHERE user_id = @my_user_id
AND (preference_nbr BETWEEN @old_preference _nbr AND
@new_preference _nbr
OR preference_nbr BETWEEN @new_preference _nbr AND
@old_preference _nbr);

Play with it a little bit. It takes a starting position in the list
and moves it up or down to the new position and slides the elements in
between either up or down.

When you want to drop a few rows, remember to close the gaps with this
code. It will start the numbering at 1 within each user.

CREATE PROCEDURE CloseUserLinksG aps(@my_user_id INTEGER)
AS
UPDATE UserLinks
SET preference_nbr
= (SELECT COUNT (U1.preference_ nbr)
FROM UserLinks AS U1
WHERE U1.preference_n br <= UserLinks.prefe rence_nbr
AND user_id = @my_user_id
AND @my_user_id = UserLinks.user_ id);

Oct 29 '06 #9
>I would really like to know how you would validate this as a URL (or email address) in a constraint. <<

I would Google it and find this website, which is full of handy regular
expressions for my constraints. This page gives ten answers.

http://regexlib.com/Search.aspx?k=URL

I guess cowboys post first and Google later :)
> The only way you are going to write a safe constraint like this is to use regular expressions and for that you'll need CLR. <<
No CLR, Tony. You need the SIMILAR TO operator in SQL-92 or a vendor
grep() functions such as Oracle and DB2 have. In SQL Server, you will
still have an ugly translation today. The x|y operator becomes <exp>
LIKE x OR <exp:LIKE y and so forth. There was an old public domain
parser for grep() to SQL Server dialect, but I cannot find it on my
disk. It probably should be re-done with CASE expressions.
>How would you write this constraint to truly validate the URL is valid and also protect yourself from a DBA making an accidental update (or malicious....)? <<
Nothing can protect you from a malicious DBA; with full DBA powers he
can destroy the world.

"On two occasions I have been asked, 'Pray, Mr. Babbage, if you put
into the machine wrong figures, will the right answers come out?' I am
not able rightly to apprehend the kind of confusion of ideas that could
provoke such a question." -- Charles Babbage

But you are confusing two different concepts; validation and
verification. A constraint can only validate a data element (This is a
syntactically correct URL) and verification (This URL actually belongs
to someone). Verification has to be external to the schema by
definition.

The way people verify a URL is to send an email to it. It is like
having a GPS tool or sextant to verify a (long, lat) location.

Oct 30 '06 #10

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

Similar topics

6
8070
by: cjm | last post by:
I need to group records and assign a setid to the group. I have a table with data that looks like this ColA ColB 94015 01065 94016 01065 94015 01085 94015 01086 33383 00912 32601 00912
5
3201
by: Lapchien | last post by:
I have list of numbers in a table (originally from autonumber in a different database) from 1 to 1,000,000. The list is not in sequential order - there are loads of numbers missing. How can I identify what numbers are missing? Thanks, Lap (I'd like to then use this 'missing number list' to use for new records, instead of autonumber -...
7
5211
by: GAVO. | last post by:
Hello every one I have a database with a form called "frmOrders" on that for I need to create a sequential number for each city apart from the original autonumber. So the table "tblorders" would look something like this: OrderID (Autonumber) SeqNo City 1 1 London 2 ...
9
5174
by: Nooby | last post by:
New to Access here. I inherited a db that has the first column as an automatically generated sequential number. I want to bump it up, but for the life of me I can't figure out how to do it. Is this type of generation a built in function of Access? I'm sure it can be written manually, but I doubt someone took the trouble to do it... Can...
2
11103
by: masker | last post by:
I was on the web trying to find a javascript that would allow me to input a number on my website and have it increase by a given percentage every second. During my search I found the Earth Population Calculator on the javascripkit.com site. The Calculator functions just as I imagine I want my number generator to function, but I need it to...
2
5182
by: simon penny | last post by:
I have a table in which I record referral records. I have a second table in which I record service records. One referral can have many service records attached. The tables are linked by referral ID - the service table incudes the referal ID field. A representation of the service table follows: Col1 Col2 Col3 Col4 1122 160 ...
15
1479
by: neelsfer | last post by:
What is easiest way to update a 2nd table used for reports in realtime as fields are filled with data The current table is called RacetimingT and the fields are: Racedate = date field racename = txtfield Racenumber = number field Racefinishtime = GeneralDate field LapNo - number field mainform = "RaceSeupF"
0
7698
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7673
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5513
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
937
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.