2
I have a table (Customer) example:
ID Nome Order 1 Joao 1 2 Ana 2 3 Marta 3 4 Joana 4
The goal is to sort the contents as follows: I get the ID (@ID) from the position to change and the new position (@novaOrdem) for that ID.
- If you receive, for example, the ID 1 for the 4th position, the data should be (Ana Marta Joana Joao)
- If you receive, for example, ID 3 for position 1, the data should stay (Marta Joao Ana)
I managed to solve my problem using a cursor (next code), however I would like to know if there was to solve without using the cursor.
DECLARE @idC BIGINT,
@ordem INT,
@OldOrdem INT,
@cont INT = 1;--cont tem que ser 1 para adicionar +1
SET @OldOrdem = (SELECT Order FROM Customer WHERE ID = @ID)
IF(@OldOrdem < @novaOrdem)
BEGIN
DECLARE Ordem_Cursor CURSOR FOR
SELECT ID, Order FROM Customer WHERE Order <= @novaOrdem AND ID <> @ID AND Order<>0 ORDER BY Order ASC
UPDATE Customer SET Order = @novaOrdem WHERE ID = @ID; /*parametro*/
OPEN Ordem_Cursor
FETCH NEXT FROM Ordem_Cursor INTO @idC , @ordem
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE Customer SET Order = @cont WHERE ID = @idC AND Order<>0
SET @cont = @cont + 1
FETCH NEXT FROM Ordem_Cursor INTO @idC , @ordem
END;
CLOSE Ordem_Cursor
DEALLOCATE Ordem_Cursor
END
ELSE
BEGIN
DECLARE Ordem_Cursor CURSOR FOR
SELECT ID, Order FROM Customer WHERE Order >= @novaOrdem AND ID <> @ID AND Order<>0 ORDER BY Order ASC-- selecionar os campos da tabela da mesma page e por ordem crescente
UPDATE Customer SET Order = @novaOrdem WHERE ID = @ID; /*parametro*/
OPEN Ordem_Cursor
FETCH NEXT FROM Ordem_Cursor INTO @idC , @ordem
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE Customer SET Order = @novaOrdem + @cont WHERE ID = @idC AND Order<>0
SET @cont = @cont + 1
FETCH NEXT FROM Ordem_Cursor INTO @idC , @ordem
END;
CLOSE Ordem_Cursor
DEALLOCATE Ordem_Cursor
END
Can anyone tell me if it’s possible? Cumps
I did not understand the ordering rule but often a CASE in ORDER BY , something like ORDER BY (CASEN WHEN P_ORDEM='N' THEN NAME ELSE END CODE) or sort according to a past parameter.
– Motta
What you really need is to leave the data already sorted in the table or when performing a query get the same sorted?
– Ascension