开发者

How to specify insertion order for rows in SQL?

How can I specify the order in which rows are inserted into a SQL database?

e.g. I would like to insert my records by date in descending order.

cmd.CommandText = "select parkname,packname,duration,bookday from book where userid='"
    + L开发者_StackOverflow社区abel15.Text + "' ORDER BY bookday DESC ";
rst = cmd.ExecuteReader();
rst.Read(); 


Don't worry about the order you insert records.

The reason is, when selecting data back using SQL, the order in which the records are returned is undetermined unless you use an ORDER BY clause. If you want to maintain table order for performance reasons, use a clustered index on the column you want to order by.

If you just wish to select the data in descending order by date, do something like the following:

select MyColumn1, MyColumn2, MyDateColumn
from MyTable
order by MyDateColumn desc


One of the features of a normalized relational database is that you do not need to worry about the order. Each row stands on its own. If you switch around 2 rows, the data is still the same and has the same meaning.

What you need is a datetime stamp. Add a field to your table that stores a datetime, then set that field's default to GETDATE(). Then whenever you do an insert, that row will be datetime stamped. Then you can use Order by in a query to present the data in the proper order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜