how to create sql server trigger and call it in mvc3 model - sql-server

I have four tables ie.
custAddress
custCompany
custContact and
custInfo
All of the table has 'cId' field common.
I have a interface in MVC3 view from which I will take inputs for all field except 'cId'. When I take input from the interface all of the above tables must be filled.
Also when I delete data, once I delete data from one table all the data from the other three table should be deleted.
I don't know how to use trigger for this. Please explain how can I do this using trigger or any other way. Any help is appreciated.

To me it sounds more like a database design problem. You do not need trigger here. Keep one of your table as primary (may be CustInfo) and have other table dependent(foreign key relationships) on this. Use cascade delete constraints on dependent tables. When you delete data from CustInfo, cascade delete constraint will take care of deleting corresponding data from dependent tables.

Related

Control Behavior of Constraints During SQL Bulk Insert?

I am curious if there is a way to control how the database responds to foreign and primary key constraints while using the bulk insert command. Specifically, I am inserting data into an employees table (with primary key empID), that is linked to data in other tables (children, spouse, and so on) by that key (empID). Given the logic and purpose behind this application, if, during bulk insert, a duplicate primary key is found, I would like to do the following:
Delete (or update) the 'employee' row that already exists in the database.
Delete all data from other tables associated with that employee (that is children, beneficiaries, and so on).
Insert the new employee data.
If I was inserting data the usual way, that is without bulk insert, I think the task would be quite simple. However, as am using it, I must admit, I am not quite certain how to approach this.
I am certainly not expecting anybody to write my code for me, but I am not quite sure if it is even possible, how to begin, or what the best approach might be. A stored procedure perhaps, or changes to schema?
Thanks so much for any guidance.
The usual solution to this kind of problem is to load the data into a Staging table, perhaps in it's own Schema or even Database. You would then load the actual table from this staging table, allowing you to perform whatever logic is required in an un-restricted manner. This has the added benefit of letting you log/audit/check the logic you are using while loading the 'real' table.

MSSQL and Entity framework syncing PK on multiple tables

I've been working with Entity framework in C# trying to figure out how to join two tables together. I found a reference here http://msdn.microsoft.com/en-us/data/jj715646.aspx on how to do this. Problem is, the two tables have PKs that are not in sync which seems to be a requirement. I've never had to worry about syncing PKs from two tables in a database before. I know I can turn off identity insert on one table but I see comments from numerous people that this is a very bad idea. If I'm not supposed to do this, then how do I accomplish syncing the PKs in each of the tables?
I have two tables in a database:
User
pkID (int)
FirstName (varchar)
LastName (varchar)
Email (varchar)
...
LockedFlags (locking fields in user from being edited)
pkID
fkUserID
bFirstName (bool)
bLastName (bool)
bEmail (bool)
I'm curious on why people thing that removing the identity insert on a table is a bad idea... if I'm relying on MSSQL to assign a PK then I could see an instance when I'm inserting a record into the database where the second table write could get a different value when dealing with multiple writes...
It sounds like you have orphaned rows in the LockedFlags table, like a row with a user ID that points to a user that has been deleted. Depending on how the relationship is setup it can also be true for the reverse.
If you have a entity where the 2 tables are combined into a single class, loading the entity set will query both tables and require matching pairs of rows.
Your LockedFlags probably has a User property which it is trying to load and cannot find in the user table.
Table options:
Note: I'm using MSSQL equivalent as I don't know MYSQL.
Comments regarding your data model:
I don't know how MYWSQL handles record locking but if it is anything like MSSQL, you do not have to worry about manually handling.
I would strongly suggest re-looking at your data model if you're going to use it as is. Just using a single table would be best if you really want to manually lock individual row fields?
Edit:
ALTER TABLE LockFlags ADD CONSTRAINT
FK_LockFlags_User FOREIGN KEY
(
UserID
) REFERENCES User
(
pkID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO

Maintaining rows in a SQL Server junction table when rows in other table are inserted and updated

Can you show sample coding to create a trigger or stored procedure that maintains rows a SQL Server junction table when changes are made to the Authors and BookTitles tables such as inserting and updating rows in those tables?
We have the following tables:
Authors:
ID
NAME
ZIP
AND SOME MORE COLUMNS
BookTitles:
ID
TITLE
ISBN
AND SOME MORE COLUMNS
This is the table we will use as our junction table:
AuthorTitles:
ID
AUTHOR_ID
BOOK_TITLE_ID
We would like to do this in a trigger instead of doing the coding in our VB.Net form.
All help will be appreciated.
The above table structures were simplified to show what we are trying to do.
We are implementing a junction table for teachers and programs.
Here is a photo of the actual system:
Unless you have Foreign Key constraints that require at least one Book per Author and/or vice-versa, then the only cases that you should need special handling are for the Deletes to BookTitles or Authors. They can be done like this:
CREATE PROC BookTitle_Delete(#Book_ID As INT) As
-- First remove any children in the junction table
DELETE FROM AuthorTitles WHERE BOOK_TITLE_ID = #Book_ID
-- Now, remove the parent record on BookTitles
DELETE FROM BookTitles WHERE ID = #Book_ID
go
In general, you want to resist the temptation to do Table Maintenance and other things like this in Triggers. As triggers are invisible, add additional overhead, can cause maintenance problems for the DBA's, and can lead to many subtle transactional/locking complexities and performance issues. Triggers should be reserved for simple things that really should be hidden from the client application (like auditing) and that cannot be practically implemented in some other way. This is not one of those cases.
If you really want an "invisible" way of doing this then just implement a Cascading Foreign-Key. I do not recommend this either, but it is still preferable to a trigger.

SQL Server constraints on foreign keys

I have an ItemComments table that has one column with a foreign key constraint linking back to an item entry in a second table. I see this as a one-to-many relationship as each item in the second table can have many comments, but no two items can be associated with the same comment entry in the ItemComments table, so a many-to-many relationship does not apply.
PROBLEM:
I want to define a constraint on this column that will prevent the foreign key value from being updated, i.e. I want to prevent someone from accidentally changing the item ID that a specific ItemComment entry is associated with. I'm not very familiar with the expression formatting of constraint check and was curious what the syntax would be for such an action. Or is there another more straightforward way of accomplishing this? Thanks for the help.
UPDATE
Is it better to implement a cross-reference table as you would in a many-to-many relationship to enforce referential integrity in this way? Or is that adding more overhead than is necessary?
You can always use a trigger. Something like:
create trigger dml_PreventUpdate
on YourTable
after update
as
if UPDATE(ItemId)
rollback
There's two types of Data Manipulation Language (DML) triggers. There's an INSTEAD OF and then an AFTER/FOR trigger (AFTER and FOR function the same way). An INSTEAD OF trigger, as the name implies, executes prior to the transaction taking place. An AFTER trigger, again as the name implies, executes after the triggered action.
Basically all this trigger is doing is testing to see if the ItemId column is updated from the UPDATE statement run against the table, YourTable. This trigger will fire every time there is an UPDATE against YourTable, but it will only ROLLBACK the transaction if ItemId is an updated field.

Cascade Delete Use Case

I am pretty new to Business Analysis. I have to write requirements that show both (for now) cascade delete (for two tables) and the rest of the tables will delete explicitly.
I need some guidance for how to write the requirements for cascade deletion.
Delete child entities on parent
deletion.
Delete collection members if collection entity is deleted.
Actually it is hard to understand the task without context and also it smells like university/colledge homework (we had one very similar to this).
Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.
If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.
For example, the all_candy table contains the candy_num column as a primary key. The hard_candy table refers to the candy_num column as a foreign key. The following CREATE TABLE statement creates the hard_candy table with the cascading-delete option on the foreign key:
CREATE TABLE all_candy
(candy_num SERIAL PRIMARY KEY,
candy_maker CHAR(25));
CREATE TABLE hard_candy
(candy_num INT,
candy_flavor CHAR(20),
FOREIGN KEY (candy_num) REFERENCES all_candy
ON DELETE CASCADE)
Because ON DELETE CASCADE is specified for the dependent table, when a row of the all_candy table is deleted, the corresponding rows of the hard_candy table are also deleted. For information about syntax restrictions and locking implications when you delete rows from tables that have cascading deletes, see Considerations When Tables Have Cascading Deletes.
Source: http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls292.htm
You don't write use cases for functionality - that is the reason why it is hard to properly answer your question - we don't know the actor who interacts with the system and of course we know nothing about the system, so we cannot tell you how to write description of their interactions.
You should write your use cases first and from them derive the functionality.

Resources