views:

22

answers:

1

The query says it all, I can't find out the right syntax without without using a WHILE loop

UPDATE Webtree SET Webtree.Sorting=w2.Sorting
 FROM
 (
  SELECT
    BranchID,
    CASE
     WHEN @Index>=ROW_NUMBER() OVER(ORDER BY Sorting ASC) THEN ROW_NUMBER() OVER(ORDER BY Sorting ASC)
     ELSE ROW_NUMBER() OVER(ORDER BY Sorting ASC)+1
    END AS Sorting
   FROM Webtree w2
   WHERE w2.ParentID=@ParentID
 )
 WHERE Webtree.BranchID=w2.BranchID
A: 

Not sure what version of SQL Server you're on - if you're on SQL Server 2005 or up, you could try and use a CTE (Common Table Expression):

; WITH BaseData AS
(
   SELECT
      BranchID,
      CASE
         WHEN @Index >= ROW_NUMBER() OVER(ORDER BY Sorting ASC) THEN ROW_NUMBER() OVER(ORDER BY Sorting ASC)
         ELSE ROW_NUMBER() OVER(ORDER BY Sorting ASC)+1
       END AS Sorting
   FROM Webtree
   WHERE ParentID = @ParentID
)
UPDATE Webtree 
SET Webtree.Sorting = base.Sorting
FROM BaseData base
WHERE Webtree.BranchID = base.BranchID

Not sure where those @Index and @ParentID values come from - they would have to be available to the CTE, of course!

The CTE creates something like an "inline temporary view" which is available to just the next statement after it. This way, you can often "disentangle" two intermixed statements and make your intent and your steps clearer (to someone else reading the code, or to yourself if you have to come back and change this in 6 months time)...

marc_s
it's Sql server 2008I tried your query and I get "Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon."
David Thorisson
It has to be the first statement in a batch - if you have stuff before it, prepend it with a semicolon (;).
marc_s
oh and the index is just the zero based index on the branch I want to move within the ParentID of the tree
David Thorisson
So @index and @parentid are defined and set "from the outside" before this statement executes?
marc_s
yep that´s right. I think I´m running out low on serum caffeine level, this query of mine is just ridicilous! I´m just having a (list item based) treeview and the query is supposed to move a single branch within the tree => move it to a new Parent item and then reorder all items within that parent (=> new Index)
David Thorisson