Hi,
Introduction:- I faced the Questions often like , How to get the last record inserted from the table?
Actual solution is, There's no way to determine the last inserted row without any identity or TimeStamp data.
But we can handle this problem in different way by writing procedure. have a look at this script
SQL Code :
In this stored procedure, we are using the cursor concept to fetch last record.
This Procedure accepts Tablename as input, and it returns last record from that table
create Procedure Get_LastRow ( -- Table name to retrieve last record @Tname Varchar(50) )
AS BEGIN -- Cursor Declaration -- By Default Cursor is Forward Only Cursor, by that we can't directly get the Last Record, -- If we want to get the last record directly, we should go for dynamic cursor EXECUTE ('DECLARE GETLAST CURSOR DYNAMIC FOR SELECT * FROM ' + @Tname)
OPEN GETLAST FETCH LAST FROM GETLAST CLOSE GETLAST DEALLOCATE GETLAST END
How To Use This:
To Execute this Procedure, follow the sample given below.
in this sample, we passed the tablename 'dbo.TableA' as parameter, it will return last record from the table if data exists, else return blank rows
EXEC Get_LastRow 'dbo.TableA'
Hope this Helps!
|
No responses found. Be the first to respond and make money from revenue sharing program.
|