How to SORT in order as entered in SQL Server?

前端 未结 5 801
猫巷女王i
猫巷女王i 2020-12-04 00:44

I\'m using SQL Server and I\'m trying to find results but I would like to get the results in the same order as I had input the conditions.

My code:

S         


        
5条回答
  •  甜味超标
    2020-12-04 01:24

    This is not an answer, just some test-code to check John Cappelletti's approach.

    DECLARE @tbl TABLE(ID INT IDENTITY,SomeGuid UNIQUEIDENTIFIER);
    
    
    --Create more than 6 mio rows with an running number and a changing Guid
    WITH tally AS (SELECT ROW_NUMBER()OVER(ORDER BY (SELECT NULL)) AS Nmbr 
                   FROM master..spt_values v1 
                   CROSS JOIN master..spt_values v2)
    INSERT INTO @tbl 
    SELECT NEWID() from tally;
    
    SELECT COUNT(*) FROM @tbl; --6.325.225 on my machine
    
    --Create an XML with nothing more than a list of GUIDs in the order of the table's ID
    DECLARE @xml XML=
    (SELECT SomeGuid FRom @tbl ORDER BY ID FOR XML PATH(''),ROOT('root'),TYPE);
    
    --Create one invalid entry
    UPDATE @tbl SET SomeGuid = NEWID() WHERE ID=10000;
    
    --Read all GUIDs out of the XML and number them
    DECLARE @tbl2 TABLE(Position INT,TheGuid UNIQUEIDENTIFIER);
    INSERT INTO @tbl2(Position,TheGuid)
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
          ,g.value(N'text()[1]',N'uniqueidentifier')
    FROM @xml.nodes(N'/root/SomeGuid') AS A(g);
    
    --then JOIN them via "Position" and check, 
    --if there are rows, where not the same values get into the same row.
    SELECT *
    FROM @tbl t
    INNER JOIN @tbl2 t2 ON t2.Position=t.ID
    WHERE t.SomeGuid<>t2.TheGuid;
    

    At least in this simple case I always get exactly only the one record back which was invalidated...

提交回复
热议问题