I want to insert a row into a SQL server table at a specific position. For example my table has 100 rows and I want to insert a new row at position 9. But the ID column whic
This kind of violates the purpose of a relational table, but if you need, it's not really that hard to do.
1) use ROW_NUMBER() OVER(ORDER BY NameOfColumnToSort ASC) AS Row
to make a column for the row numbers in your table.
2) From here you can copy (using SELECT columnsYouNeed INTO
) the before and after portions of the table into two separate tables (based on which row number you want to insert your values after) using a WHERE Row < ##
and Row >= ##
statement respectively.
3) Next you drop the original table using DROP TABLE
.
4) Then you use a UNION
for the before table, the row you want to insert (using a single explicitly defined SELECT
statement without anything else), and the after table. By now you have two UNION
statements for 3 separate select clauses. Here you can just wrap this in a SELECT INTO FROM
clause calling it the name of your original table.
5) Last, you DROP TABLE
the two tables you made.
This is similar to how an ALTER TABLE
works.