MSQL: Delete rows from VIEW

12,030

Solution 1

Usually, a view isn't something you can delete from; it's kind of a virtual table, which shows you the rows from one or more real tables in the database. If you want a row to disappear from a view, you need to either delete the data from the real tables behind the view, or alter the view-creating SQL so that that particular row won't be shown in the view. With some simpler views you can DELETE FROM (and update) a view; however, even so the data is actually deleted from the real table.

You also cannot generally add anything to a view; if you need completely new data, it has to be added in the real table(s) from which the view is created.

For view basics, see for example http://www.w3schools.com/sql/sql_view.asp

Solution 2

If your view is updatable - really depends on a database you are using and the way view was created. General rule (again, varies from one DB to another) there should be one table and no aggregates in the select statement, creating the view.

Here is details for MySQL: http://dev.mysql.com/doc/refman/5.7/en/view-updatability.html

And for SQL Server: https://msdn.microsoft.com/en-CA/library/ms187956.aspx

InterSystems Caché: http://docs.intersystems.com/cache20152/csp/docbook/DocBook.UI.Page.cls?KEY=GSQL_views#GSQL_views_update

Share:
12,030
bpesunny
Author by

bpesunny

Updated on June 15, 2022

Comments

  • bpesunny
    bpesunny almost 2 years

    Is it possible to delete rows from a View?

    • jarlh
      jarlh over 8 years
      Views don't contain data, tables do. You can perhaps do DELETE FROM viewname.
    • bpesunny
      bpesunny over 8 years
      The probles is that it deletes the view, and then by insert it creates a table instead of a view.
    • jarlh
      jarlh over 8 years
      DELETE doesn't drop any view... DROP VIEW drops a view!
    • jarlh
      jarlh over 8 years
      MSQL? Do you mean MS SQL Server?
    • a_horse_with_no_name
      a_horse_with_no_name over 8 years
      insert doesn't create new tables, it creates new rows in an existing table.
    • Revious
      Revious almost 5 years
  • jarlh
    jarlh over 8 years
    Some views are updatable, e.g. "select * from base_table". So INSERT, UPDATE and DELETE can be used on the view (and the base table's data is changed...)
  • Juha K
    Juha K over 8 years
    Thanks, I wasn't aware of that! I'll change my answer to reflect this.
  • a_horse_with_no_name
    a_horse_with_no_name over 8 years
    You can even make views with a join updateable using instead of triggers