Saturday, February 25, 2012

Returning Only 5 Rows

Not sure if this should be somewhere in the C# forum or the datagrid forum or in the SQL forum. I have a Windows Application written in C# that is accessing SQL Server 2005 (express I believe). The program loads up and the first form has a datagrid on it. The datagrid is bound to a sql query getting all rows from 1 of the tables, and displays them in the datagrid in descending order by date. Everything there is fine.

What I want to do is have the datagrid only show the last 5 entries (by date). I'm pretty sure this is possible but I'm not sure if it's done in the SQL query of if it's done somewhere in the datagrid (or somewhere in the binding).

Here is my SQL query so far...
[code]

SELECT transactionID, accountID, amount, type, description, notes, date
FROM Transactions
ORDER BY date DESC

[/code]

I believe in mySQL there was a LIMIT 5 parameter I could use, but that just produces an error here.

Thats an easy opne, have a look at the TOP operator:

SELECT TOP 5 transactionID, accountID, amount, type, description, notes, date
FROM Transactions
ORDER BY date DESC

Furtherone and due to the fact that you are using 2k5 you should have a look on ROW_NUMBER() which introduces a new feature of SQL 2k5 and can e.g. be used for pagination.

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

No comments:

Post a Comment