Click here to Skip to main content
15,908,264 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear Friends


How can Select Only last Row of the Table Using Sql


if i have Table 100 rows now i want Select 99th row without passing field name

eg i have table like this

openingBalance Purchase Sale ClosingBalance
100 10 10 100
100 20 10 110
110 25 30 105
105 100 5 200
200 20 10 210
210 55 100 465


in this i want Select last Row
Posted
Updated 15-Mar-21 14:57pm

It's not difficult to select the first or last row - that's just a case of ordering your inputs and using SELECT TOP 1:
SQL
SELECT TOP 1 * FROM MyTable ORDER BY MyColumn ASC
Will give you the first, and
SQL
SELECT TOP 1 * FROM MyTable ORDER BY MyColumn DESC
will give you the last.
In your case however, it may not be possible at all because you have no column on which to sort - and if you do not specify a sort order then SQL is at liberty to return rows in any order it sees fit - and that order can change between two successive runs if SQL decides to reorganise it's tables for greater efficiency.

I think you need to look at adding a column to your table which "date stamps" each row according to when it was created to allow you a positive ordering mechanism. If you don't, then any other solution which works at present may fail randomly in the future, with potentially harmful results.
 
Share this answer
 
select top 1 * from Table_Name order by ID desc
 
Share this answer
 
I think that is the answer to your question

SQL
select top(1) * from YourTable order by First-Field-Of-Table desc


first field = praimer key or identity
 
Share this answer
 
v2
Try the following code. . .
SQL
DECLARE @MYVAR NVARCHAR(100)
Declare @MyVar2 nvarchar(100)
DECLARE MYTESTCURSOR CURSOR
DYNAMIC 
FOR
SELECT EmpID,EmpName FROM Employees
OPEN MYTESTCURSOR
FETCH LAST FROM MYTESTCURSOR INTO @MYVAR,@MyVar2
CLOSE MYTESTCURSOR
DEALLOCATE MYTESTCURSOR
SELECT @MYVAR,@MyVar2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900