如何删除asp.net中SQL Server表的前n行?

时间:2016-05-04 04:57:22

标签: sql-server vb.net

我想删除(例如)我的SQL Server数据库中的前5行。我使用下面显示的代码,但它不起作用。我怎么能得到这个?

    Dim con As New SqlConnection(connectionString)

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

3 个答案:

答案 0 :(得分:3)

See this link

根据您的表和数据库名称进行更改。如果你想

,也可以订购
  cmd.CommandText = ";WITH CTE AS ( SELECT TOP 5 * FROM PubTb )  DELETE FROM CTE"

答案 1 :(得分:1)

使用subquery根据任何列选择所需的顶行。然后删除 比如

DELETE FROM PubTb WHERE ID IN (SELECT TOP 5 ID FROM PubTb ORDER BY ID DESC)

答案 2 :(得分:0)

那里不需要CTE。

DELETE From PubTb 
FROM PubTb original INNER JOIN
(SELECT TOP 5 ID FROM PubTb /* you may order it */) topfive
ON original.ID = topfive.ID