3

I am doing something like this in SP,

insert into @FilteredTbl select * from @MasterTbl

but now problem is that i want data of @MasterTbl sorted before adding into @FilteredTbl,

How can I do that ?

IT ppl
  • 2,626
  • 1
  • 39
  • 56

7 Answers7

4

Maybe something like this:

INSERT INTO @FilteredTbl 
SELECT * FROM @MasterTbl AS tbl
ORDER BY tbl.OrderbyColumn
Arion
  • 31,011
  • 10
  • 70
  • 88
  • 7
    Am I missing something here....aren't all these solutions incorrect? The order is not guaranteed. _"4. INSERT queries that use SELECT with ORDER BY to populate rows guarantees how identity values are computed but not the order in which the rows are inserted"_ http://blogs.msdn.com/b/sqltips/archive/2005/07/20/441053.aspx – user3811205 Mar 03 '15 at 23:41
  • Yes the above Query wont work as explained in the above link. – maxspan May 04 '16 at 13:25
3

Try following method to insert sort result into temp table. Use ROW_NUMBER to ORDER BY table result

DECLARE @FilteredTbl AS TABLE
(
    RowID INT
    [Column_1]
    [Column_2]
      .
      .
)

insert into @FilteredTbl 
select ROW_NUMBER()OVER(ORDER BY [ShortColumn]),[Field_1],[Field_2]... from @MasterTbl
  • With out "ROW_NUMBER()", inserting data into a temp table with ordering is not working. working only with "ROW_NUMBER()" . thanks Jaylem – Sajith A.K. Oct 25 '17 at 11:22
0

I had the same problem and solved it with adding id as identity to the declared table

in your case:

@FilteredTbl
 ID int identity not null,
 your columns...

When inserting sorted data it still sorted as it was

mozway
  • 194,879
  • 13
  • 39
  • 75
Qusay
  • 1
  • 2
-1

You should add identity your table then It will sorted like that

CREATE TABLE #test (
    s int IDENTITY (1, 1),
    ID int,
    Name varchar(50),
    part int
);

INSERT INTO  #test (ID,Name,Part)
SELECT ID, Name, Part FROM Table_1 ORDER BY ID DESC
SELECT * FROM #test 
KittMedia
  • 7,368
  • 13
  • 34
  • 38
Eray
  • 1
  • 1
-1

You can use order by class in select statement

insert into @FilteredTbl 
    select * from @MasterTbl
    order by <column name>
-1

Please sort the table as you want before inserting into another table.

Like:

Select * From @MasterTbl m Order By m.ColumnName

then insert into your new table

Insert Into @FilterTbl Select * From @MasterTbl m Order By m.ColumnName [DESC]

You can also filter your @MasterTbl using Where Clause

Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154
-1
INSERT INTO @FilteredTbl SELECT * FROM @MasterTbl AS mtb ORDER BY mtb.OrderbyColumn [desc]

Here desc is optional if you want to order by your column in descending order than add ir otherwise no need to add

raina
  • 81
  • 1
  • 3
  • 8