Welcome to Dream.In.Code
Getting Help is Easy!

Join 136,067 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,594 people online right now. Registration is fast and FREE... Join Now!




How to Insert record at top row of table? (MS SQL Server)

2 Pages V  1 2 >  
Reply to this topicStart new topic

How to Insert record at top row of table? (MS SQL Server)

davkav
8 Apr, 2008 - 01:46 AM
Post #1

New D.I.C Head
*

Joined: 11 Mar, 2008
Posts: 35



Thanked: 1 times
My Contributions
Hi Guys,

Ive done some searching and strangley I couldnt find an answer. I thought this would have come up often enough rolleyes.gif

Basically all I want to do is write a new record to Row No.1 in my table and move the present data in the table down i.e. Row 1 moves to 2 and Row 2 moves to 3 and so on...


CODE

    sqlStr = "insert Tank_Level(Date_Time,Tank_Level1,Tank_Level2,Setpoint1,Setpoint2) Values('" & Now() & "','" & MyText(1).Text & "','" & MyText(2).Text & "','" & frmStatus.MyText(5).Text & "','" & frmStatus.MyText(6).Text & "')"



I have the above code in my VB program.

Table name is Tank_Level

Column names are:
Date_Time
Tank_Level1
Tank_Level2
Setpoint1
Setpoint2

Oh one more thing, if i want to read from my database into excel i use this code
CODE

     MyConnObj.Open "PROVIDER=MSDASQL;driver={SQL Server};server=PC125\SQLEXPRESS;uid=;pwd=;database=TEST;"
    
     sqlStr = "select * from Tank_Level"
        
     myRecSet.Open sqlStr, MyConnObj, adOpenKeyset

     frmBPage.Print "Date / Time"; Tab; Tab; "Tank Level 1"; Tab; "Tank Level 2"; Tab; "Setpoint 1"; Tab; "Setpoint 2";
     frmBPage.Print ""
    
     While Not myRecSet.EOF
        
         frmBPage.Print myRecSet(0); Tab; myRecSet(1); Tab; myRecSet(2); Tab; myRecSet(3); Tab; myRecSet(4); vbNewLine;
         myRecSet.MoveNext
    
     Wend



How can i just pull the last 5 entries in the database as in the latest 5?

Thanks again guys

This post has been edited by davkav: 8 Apr, 2008 - 02:45 AM
User is offlineProfile CardPM
+Quote Post

davkav
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
15 Apr, 2008 - 01:47 AM
Post #2

New D.I.C Head
*

Joined: 11 Mar, 2008
Posts: 35



Thanked: 1 times
My Contributions
Bump?
User is offlineProfile CardPM
+Quote Post

1lacca
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
15 Apr, 2008 - 03:19 AM
Post #3

code.rascal
Group Icon

Joined: 11 Aug, 2005
Posts: 3,822



Thanked: 11 times
My Contributions
Usually it is the internal matter of the database where your record is stored.
Even two consecutive select query is allowed to return the results in different order (if no sorting is specified)
So if you want to sort your records in a specific order, then specify an order by clause in your select and a column that defines the place of the given record. You can put the rank of that record into your custom column.
When you want to push the whole thing down, simply run an update that increases the rank by one, and set the rank of the new record to one.

User is offlineProfile CardPM
+Quote Post

baavgai
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
15 Apr, 2008 - 06:15 AM
Post #4

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,019



Thanked: 105 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
What 1lacca said, database don't care about order. Now you said:

QUOTE(davkav @ 8 Apr, 2008 - 05:46 AM) *

Basically all I want to do is write a new record to Row No.1 in my table and move the present data in the table down i.e. Row 1 moves to 2 and Row 2 moves to 3 and so on...


WHY?!? This is a very bad idea. There's a reason no one would tell you how to do it. You should never be concerned with who's first, only if there is valid data that you can use to get the results you need. So, you want to order the data by based on sequence of insertion? Not a problem, SQL Server has an auto number mechanism built in...

In your table, add an IDENTITY column. We'll call it Seq. You usually plan for them in table creation, e.g.
CODE

create table Tank_Level(
    Seq int IDENTITY(1,1) NOT NULL,
    Date_Time datetime...


But you can put it in with an "Alter Table" if you need to.

Now, the identity column is sequential, it increments on each insert. You want the last row to be the first row? Simple, just present it that way:
CODE

select * from Tank_Level order by Seq desc


You can even grab the current max number, if you want to display Seq in a reverse order:
CODE

select (Seq-IDENT_CURRENT('Tank_Level'))+1 as Seq
    from Tank_Level
    order by Seq desc


Hope this helps.

User is online!Profile CardPM
+Quote Post

2457
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
15 Apr, 2008 - 05:41 PM
Post #5

D.I.C Head
**

Joined: 9 Apr, 2008
Posts: 72

The beuty of database like this, is You sort the data qhen You query it.
It will allways be sorted by some logic, do not treat data tables like excel tables.

So, if You add an "auto increasement" ID to each row, and query by that You can sort the rows by time of adding them relative each other.
(mm so the highest ID will be the lastone added, the lowest ID will be the firstone added)


User is offlineProfile CardPM
+Quote Post

davkav
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
16 Apr, 2008 - 01:55 AM
Post #6

New D.I.C Head
*

Joined: 11 Mar, 2008
Posts: 35



Thanked: 1 times
My Contributions
Thanks guys. Yeah i think i have it stuck in my head thinking like excel.

Never even dawned on me to use a Index column, im a noob at DB smile.gif

One thing though. I have the Seq column as the last column in my design and it auto increments. but when i try to write to the database now, in VB, its asking for data to be written because i now have 6 columns.

CODE

    sqlStr = "insert Tank_Level(Date_Time,Tank_Level1,Tank_Level2,Setpoint1,Setpoint2) Values('" & Now() & "','" & MyText(1).Text & "','" & MyText(2).Text & "','" & frmStatus.MyText(5).Text & "','" & frmStatus.MyText(6).Text & "')"



I suppose i want something like this
CODE

    sqlStr = "insert Tank_Level(Date_Time,Tank_Level1,Tank_Level2,Setpoint1,Setpoint2,Seq) Values('" & Now() & "','" & MyText(1).Text & "','" & MyText(2).Text & "','" & frmStatus.MyText(5).Text & "','" & frmStatus.MyText(6).Text & "'#########)"


I inserted Seq at the end of the insert statement but what do i put in the values statement where the hashes are?
User is offlineProfile CardPM
+Quote Post

baavgai
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
16 Apr, 2008 - 04:47 AM
Post #7

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,019



Thanked: 105 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
The first syntax looks fine, except I believe "insert INTO Tank_Level" may be required. You never insert an auto increment field, they won't even let you unless you ask real nice.

Also, if all you're doing for Date_Time is passing a now, you should let the database pick the current time. e.g.
CODE

sqlStr = "insert into Tank_Level(Date_Time,Tank_Level1,Tank_Level2,Setpoint1,Setpoint2) Values(" _
      & GetDate()," _
      & "'" & MyText(1).Text & "','" & MyText(2).Text & "','" & frmStatus.MyText(5).Text & "','" & frmStatus.MyText(6).Text _
      & "')"


Even better you can make the Date_Time have a default value of GetDate() and never have to insert it again.

Also, please use bind parameters. Friends don't let friends get SQL Injected. tongue.gif

User is online!Profile CardPM
+Quote Post

davkav
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
16 Apr, 2008 - 05:37 AM
Post #8

New D.I.C Head
*

Joined: 11 Mar, 2008
Posts: 35



Thanked: 1 times
My Contributions
Legendary Thanks Guys! icon_up.gif biggrin.gif icon_up.gif biggrin.gif genius.gif

This post has been edited by davkav: 16 Apr, 2008 - 05:38 AM
User is offlineProfile CardPM
+Quote Post

ultimitloozer
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
28 Jun, 2008 - 08:11 PM
Post #9

New D.I.C Head
*

Joined: 27 Jun, 2008
Posts: 6



Thanked: 1 times
My Contributions
It looks like this Seq field is not even required. The entire process could have been done using the Date_Time field instead. A simple descending sort on that field would yield the same results.
User is offlineProfile CardPM
+Quote Post

1lacca
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
29 Jun, 2008 - 03:21 AM
Post #10

code.rascal
Group Icon

Joined: 11 Aug, 2005
Posts: 3,822



Thanked: 11 times
My Contributions
Theoretically (and in practice) two records can have the same date_time value.
User is offlineProfile CardPM
+Quote Post

ultimitloozer
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
29 Jun, 2008 - 04:28 AM
Post #11

New D.I.C Head
*

Joined: 27 Jun, 2008
Posts: 6



Thanked: 1 times
My Contributions
If the date_time field is of the datetime data type, its granularity is approximately 3.33ms. Unless the data is being inserted faster than one every 5 ms, the data in that field should be unique. (And if he is pushing data in that fast, I would hate to be the one ensuring that he has enough drive space for the massive growth of the database files!) This would change if the data type is smalldatetime which has a granularity of about 1 minute and would push the gap between inserts to 90 seconds to guarantee a unique stamp.
User is offlineProfile CardPM
+Quote Post

1lacca
RE: How To Insert Record At Top Row Of Table? (MS SQL Server)
29 Jun, 2008 - 05:06 AM
Post #12

code.rascal
Group Icon

Joined: 11 Aug, 2005
Posts: 3,822



Thanked: 11 times
My Contributions
QUOTE(ultimitloozer @ 29 Jun, 2008 - 02:28 PM) *

If the date_time field is of the datetime data type, its granularity is approximately 3.33ms. Unless the data is being inserted faster than one every 5 ms, the data in that field should be unique. (And if he is pushing data in that fast, I would hate to be the one ensuring that he has enough drive space for the massive growth of the database files!)

It is enough if data is pushed at the same time once, and it CAN happen only if a total of 2 records are inserted (Murphy's law and some nice examples at the Daily WTF). I know that this seems to be a theoretical debate from one side, but such design decisions can lead to systems failing spectacularly and misteriously. Sequences/auto increment fields were invented for a reason, and this is one of them. It is not the only solution, but using any kind of date_time type in such a scenario is a design fault.
User is offlineProfile CardPM
+Quote Post

2 Pages V  1 2 >
Fast ReplyReply to this topicStart new topic
Time is now: 12/1/08 06:48PM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month