user1605859 user1605859 - 2 years ago 83 Question

How to delete top n rows of a sqlserver table in

I want to delete (for example) top 5 rows in my sql server database. I used the below code but it does not work. How may I get this?

Dim con As New SqlConnection(connectionString)
Using cmd = New SqlCommand()
cmd.CommandText = "DELETE From PubTb TOP 5"
cmd.Connection = con
Dim numberDeleted As Integer = cmd.ExecuteNonQuery()
End Using

Answer Source

See this link

Change it as per your table and Database name. Also order it if you want to

  cmd.CommandText = ";WITH CTE AS ( SELECT TOP 5 * FROM PubTb )  DELETE FROM CTE"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download