Wednesday, March 21, 2012

last row in a table

How can we get the last row in a table

thanksTo go along the lines of true database design, you, as the dba/programmer must set a means of determining which record is the "last" record. As you see a database is not necessarily how it's stored, and you must organize your records by either date or identity to determine what was the last insert. Only time you can get the last record inserted is when you're actually doing the insert. Once that transaction is complete, w/o the proper fields applied to sort upon, you're just out of luck.|||Actually what I was trying to do is the following,
I was developing a web application on my pc. One of the tables of the database I was using had an ID field that was an autonumber and I didn't need to insert anything in it, since it used to insert an autonumber by itself. I published the application on europe.webmatrixhosting.net, so I copied my tables to their database. Now when I copied the table, that field became no longer an autonumber, so it gave me an error when I was trying to insert a row telling me that I can't insert null in that field.
So I thought that if I can just get the last row in that table and I increment the id of that row and make it the id of the new row.

Is there a better way of doing it??

Thanks for the help|||Alter the table to make that field an autonumber field again.

Now a big issue is how you "copied" the table over. I'd have generated a script to get the backbone of the tables with all the indexes and such, then executed that on the other server. THEN export the data over.

Hope this helps.|||I'm sorry but I'm not into sql so much, but how can I make it an autonumber with sql|||


Alter YourTable
Alter IdentityColumn int IDENTITY
|||If you do not supply a seed and an increment, 1 will be used for both, which is probably not what you want. Use 1 greater than the current highest ID in your table for the seed so that you do not create duplicate IDs:

Alter YourTable
Alter IdentityColumn int IDENTITY(8765,1)

Terri|||What the other guys suggested is your best bet, but in case that doesn't work for some reason, there's another way you can go here. You can create another table that contains only one column and one row. This row will store the last "autonumber" that you used. So what you can do when you're performing the insert is query this table, get the number, use that number to make your insert, and then call an update on the "autonumber" table to increment the value by 1 (or whatever increment you want to use).

Also, you need to make sure that you lock the "autonumber" table to make sure that nobody else can make a change to that value while you're working with it, which could cause integrity issues.

However, this is simply an alternative, albeit a worse one than what the other two posters provided. If you can, use their suggestion.|||thanks guy, you really helped me alotsql

No comments:

Post a Comment