Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete first 2 records

Status
Not open for further replies.

Per9922

IS-IT--Management
Oct 1, 2004
74
0
0
SE
Hello,

I need the help from you! I would like to delete the first two records. I have tried this:

DELETE FROM LoggingData WHERE (SELECT TOP 2 * FROM LoggingData ORDER BY DateAndTime)

Please help!
 
Found the solution:

DELETE FROM LoggingData Where DateAndTime In (SELECT TOP(2) DateAndTime FROM LoggingData ORDER BY DateAndTime)
 
WHERE conditions have to be boolean expressions, a query returns records. A boolean expression can be made if you specify records should be IN a lit of records, but you typically need an ID (primary key field) to identify what is IN the set of records or not, eg

DELETE FROM LoggingData WHERE LoggingData.ID IN (SELECT TOP 2 ID FROM LoggingData ORDER BY DateAndTime)

As the order is given by dateandtime it would be sufficient to do it this way, I think:

DELETE FROM LoggingData WHERE LoggingData.DateAndTime IN (SELECT TOP 2 DateAndTime FROM LoggingData ORDER BY DateAndTime)

Bye, Olaf.
 
You can also use a CTE
Code:
;WITH CTE AS
(
SELECT TOP 2 *
FROM [LoggingData ]
 ORDER BY DateAndTime
)
DELETE FROM CTE
 
Nice, I tried it and can confirm.
What would it do in situations you do joins in the CTE?

I see, that'll give "Msg 4405...View or function 'CTE' is not updatable because the modification affects multiple base tables."
But with a single table query this works.

Bye, Olaf.
 
Thanks Olof & jbenson001 for the respone! You are so helpful!! Thanks and have a nice weekend
 
@Per9922 you are welcome

@Olaf - In order to avoid that error you would have to do the join to the cte outside of the cte definition.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top