Insert new column into sql view - mysql

Can i add new column into sql view and update that column with new data?

Actually View is nothing, it's a virtual existent of table. If you are updating the data, it mean you are updating in corresponding tables.
A view can be used in a query that updates data, subject to a few restrictions. Bear in mind that a view is not a table and contains no data—the actual modification always takes place at the table level. Views cannot be used as a mechanism to override any constraints, rules, or referential integrity defined in the base tables.
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
You can refer following article for more info.
http://www.informit.com/articles/article.aspx?p=130855&seqNum=4
hope this will help you.
thanks

Related

How to store modifications without changing the original DB record

I'm building an app in which users can create entities that are stored in my Entity table with some caracteristics like "space_below" and "width". Users can also create their own groups of entities by choosing amongst everybody's entities. Once they picked someone else's entity, I want them to be able to modify some caracteristics like the "width" and save these modifications for their own group. What would be to best way to do that in my DB?
First approach
Each time a user do a modification, create a new record (almost a duplicate) in the Entity table and then only refer to this new entity from the group where it was change.
In this case, I would need to add a column to my Entity table to differentiate original entites from copied entites.
Second approach
In any scenario, I will have a junction table between the Group table and the Entity table. In this junction table, I could add a "modification" column in which I store a JSON with the modifications. Something like { space_below: '8', width: '200' }. If there is no modficiation, the value of the column will be null.
I think I prefer the second approach since the first one involves a lot of duplicated data in the Entity table, but might not be aware of other implications.

MySQL Id columns

I am working on a project that is an upgrade of an existing system.
The existing DB structure must be kept intact as there is a system reading the same DB that will be used ontop of the new system.
I am building a new CMS / Management system using a PHP framework that expects so see all DB table autoincrement ID field named simply "id" - I do not want to modify the PHP deal with anything other that "id" as this field name - trust me it will be a massive task.
The existing DB has non standard Autoincrement ID field naming, eg:
"iBmsId" -shcema: i=INT Bms = the name of the table, Id = ID....
Is there anything I can do to the DB itself to make a duplicate of the "iBmsId" column, to create a matched column called simply "id" that has the corresponding INT values? This way my new system will function as expected without having to do a serious re-write, and at the same time still have the existing system able to communicate with the DB?
In this situation you can just use VIEW :)
http://dev.mysql.com/doc/refman/5.0/en/create-view.html
View in dbms is like a virtual table (unless it's materialized). Views add a new abstraction layer which can support independency between how you use db and how it's implemented. It can also increase security for example by hiding some fields or making view readonly.
Notice: In order to add view transparently you can rename origin table and create the View with origin table name. This let's you avoid modifications in existing code.
You can read here how to create updatable and insertable view (which can behave as normal table).
If only one system at a time is modifying the value, then you can use a view:
create view v_table as
select t.*, iBMid as id
from table t;
Presumably, an auto-incremented value is not going to be updated, so this should be safe. However, keep in mind that:
To be more specific, a view is not updatable if it contains any of the following:
. . .
Multiple references to any column of a base table.
This could affect other columns that you might want to treat the same way.

MySql Soft delete

I have an existing application (with MySQL DB).
I just got a new requirement where I need to delete some records from one of main entity. I dont want to apply hard delete here as its risky for whole application. If I use soft delete I have to add another field is_deleted and because of that i have to update all my queries (like where is_deleted = '0').
Please let me know if there is any smarter way to handle this situation. I have to make changes in half of the queries if I introduce a new flag to handle deletes.
Your application can run without any changes. MySQL is ANSI-SPARC Architecture compliant . With external schema you achieve codd's rule 9 "Logical data independence":
Changes to the logical level (tables, columns, rows, and so on) must
not require a change to an application based on the structure. Logical
data independence is more difficult to achieve than physical data
independence.
You can rename your tables and create views with original table names. A sample:
Let's supose a table named my_data:
REMAME TABLE my_data TO my_data_flagged
ALTER TABLE my_data_flagged
ADD COLUMN is_deleted boolean NOT NULL default 0;
CREATE VIEW my_data AS
SELECT *
FROM my_data_flagged
WHERE is_deleted = '0'
Another way is create a trigger and make a copy of erased rows in independent table.
Four suggestions:
Instead of using a bit called is_deleted, use a dateTime called something like deleted_Date... have this value be NULL if it is still active, and be a timestamp for the deletion date otherwise. This way you also know when a particular record was deleted.
Instead of updating half of your queries to exclude deleted records, create a view that does this filtering, and then update your queries to use this view instead of applying the filtering everywhere.
If the soft deleted records are involved in any type of relationships, you may have to create triggers to ensure that active records can't have a parent that is flagged as deleted.
Think ahead to how you want to eventually hard-delete these soft-deleted records, and make sure that you have the appropriate integrity checks in place before performing the hard-delete.

How do I ensure rows inserted into a SQL view will be elements of that view?

Here is the scenario:
I have a simple 'Inventory' table. This table has three columns: one foreign key that references a product, one foreign key that references a store, and one numeric value for the price. This table doesn't specify the amount of a product available, it just is used to inform users that a store sells a particular product.
This Inventory table is publicly viewable (that is the whole point of the application: users should be able to search for different products among various - potentially unrelated - stores). The stores need to be able to update their own inventories, without affecting the inventories of other stores.
Now, each store has its own user account and view. The views are essentially set up as follows:
CREATE VIEW MY_INVENTORY AS SELECT I.ProductID, I.StoreID, I.Price FROM Inventory I WHERE I.StoreID = id
Each store has full permission on its own inventory view, so that each store can add items to its inventory, update them, etc.
Here is the snag: Each store can add items to this view with a StoreID that does not match their own StoreID! In this way, they can add items to other stores' inventories (which is certainly a no-no).
I have already created a front-end application for accessing the database, and it is easy enough to programmatically ensure that no store affects another stores inventory, but I want better security than that. How do I go about enforcing this at the database level? Triggers? Constraints? I've looked into both and I'm not exactly sure how to go about this.
One last thing: only the DB root account and individual stores have access to individual stores' views.
I think you can get what you want by creating your view with the WITH CHECK OPTION clause. This will prevent anyone from using the view to insert information that does not match the view's Where clause, so if a store's view is for "Where StoreID = 500", it cannot use that view to insert records for store 501.
According to the MySQL documentation here,
The WITH CHECK OPTION clause can be given for an updatable view to prevent inserts or updates to rows except those for which the WHERE clause in the select_statement is true. The WITH CHECK OPTION clause was implemented in MySQL 5.0.2.
In a WITH CHECK OPTION clause for an updatable view, the LOCAL and CASCADED keywords determine the scope of check testing when the view is defined in terms of another view. The LOCAL keyword restricts the CHECK OPTION only to the view being defined. CASCADED causes the checks for underlying views to be evaluated as well. When neither keyword is given, the default is CASCADED.
For more information about updatable views and the WITH CHECK OPTION clause, see Section 17.4.3, “Updatable and Insertable Views”.
You cannot enforce this at the database level; you're going to have to enforce this on the server side, probably by a check at the scripting level (PHP, Python, whatever) that the store ID of the entry potentially being added matches the Store ID assigned to the user.

Updatable views - SQL Server 2008

A question about updatable db views: I'm reading through some MSDN documentation on the subject, and I come across the following restriction:
Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
I just want to be sure I understand the restriction. I'd like to use views in a couple of my media review projects. The relational data is spread throughout tables, but a view seems to be the best way to be able to consolidate the data I need from multiple tables (some of which are linked via foreign keys) into a centralized location. Since the columns would come from a variety of tables, does this mean I can't run one blanket INSERT or UPDATE to persist changes in all the columns?
You can use an INSTEAD OF trigger on a view to keep your application only dealing with the view instead of the collection of base tables the view references.
Here is an example : Designing INSTEAD OF Triggers
Yes that's what it means. I see no advantage to updating through a view since you have to know what the base tables involved are anyway.