1

I am looking for the best way to update the value I store on the following structure:

Table: Pages

Fields:

  1. id (int)
  2. bookid (int)
  3. pageorder (int)
  4. filename (string/varchar)

So I have the book order and a page number. I need to insert a page before the page number I have, lets say 25, and update all the other pages to have 1 added to their pageorder value.

Can I do this without pulling a list and cycling threw it running updates, or is that the best way to go about it?

Thanks!

2 Answers 2

7
declare @newpage int
set @newpage = 25
update pages set pageorder = pageorder +1 where pageorder >= @newpage and bookid = @bookid

something like that?

Sign up to request clarification or add additional context in comments.

4 Comments

Looks like it is working, thanks a million! Will accept when I can.
Probably want to filter by bookid, otherwise that's going to end badly.
Yes I only gave a very rough prototype - you definitely want to add filtering so you don't update EVERY book.
Ya I figured, but your answer gave me the bit of information that somehow slipped out of my mind.
2

Strictly with SQL, Like this

update pages 
set pageorder = pageorder + 1
where bookid=@bookid
and pageorder >= @pageorder;

insert into Pages
(id,bookid,pageorder,filename)
values
(@id,@bookid,@pageorder,@filename);

3 Comments

You want to be careful to do your update first, otherwise you'll end up with two page 25's after the insert that'll both become page 26 after the update.
Not sure its worthy to downvote. The accepted answer doesnt even filter by bookId :p That can end up even worse.
I'm assuming the downvote is because initially because I had the insert first. The funny part is that I actually made a mental note to do the update first, then proceeded to type it wrong. Oh well, fixed now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.