I have 2 tables, A and B with an int
primary key and a string
name.
I have a 3rd table, C, with 2 columns that map the IDs of A and B together. I want to create a view to edit the mappings in table C, but I want the view to show the Name
value rather than the IDs
. The view would be edited via SQL Server Management Studio.
For example, the view should allow the user to type in "Item4" in the item column, and "Accessory1" in the accessory column, and table C gets updated with a new row mapping "4" to "1".
I am wondering if I can make this an editable view so I don't have to go to the trouble of writing a whole application to manage this.
If I go to the view in Microsoft SQL Server Management Studio, and right click, I can edit the top 200 rows. I know the constraint on this feature is that I can only edit if the change is to a single table. I would only be editing a single table, so there might be a way to get this to work. Is there a way? (My users are people (traders) who are familiar with SQL Server and prefer to have direct access to their data).
Best Answer
Base tables
Sample data
View
Problem
The view is not directly updatable:
Solution
We can make any view updatable using an instead of trigger:
The trigger essentially converts the supplied names to IDs before the insert is attempted. As long as you have good referential integrity, the need for additional checks in the trigger code should be minimal. The details depend on exactly what you want to happen if someone pastes multiple entries, only some of which are valid, for example.
Inserts, updates, and deletes
You would need additional trigger logic if you want to allow (general) updates and deletes through the view. For example: