views:

29

answers:

1

I need to update the record status(field name IsActivate-this holds the status of record) but needs to check first if the data is used in another table(meaning table is having a relationship with another table).If the data that I want to update is used in another table, update is not allowed else it should be updated.How can I can create trigger to achieved this approach using MS SQL 2005?Or this can be achieved using SP?How?

+2  A: 

I would avoid using a trigger for this if i were you. You can easily do this in an SP.

Your SP for updating the record should do something like this:-

  • I assume that the value you want to check is being passed to update SP, likely in a parameter eg @value
  • Use @value in a SELECT statment in something like SELECT @result = count(1) FROM tableToCheck WHERE columnToCheck = @value
  • If @result = 0, go ahead and fire your existing UPDATE statement
  • If @result <> 0, do whatever you need to do in your business scenario like maybe update an Output param to indicate that your update failed

In case you want to know the syntax of the above logic, you can look up MSDN if you are using SQL Server or the MySQL docs if using MySQL or Oracle help if you are using Oracle. If any other engine, just google "CREATE PROCEDURE <engineName>"

And then if you have any specific questions with the syntax, feel free to post them here with your code and we will be glad to help you with them!!

InSane
hi InSane, what are the disadvantages if using this in trigger, just curious...:)
@user335160 - Debugging triggers is usually a big pain because of the inherent nature of triggers...they are almost always the last place anyone looks in and most people forget about them!! That, to me, in the long term, is probably their biggest disadvantage
InSane
but how about the performance?it is much slow than SP?By the way the table is having a relationship with 5 tables, so meaning to say I have to create the given statement 5 times to check if the value exists?
@user335160 - i must say that i do not have detailed information on their relative performance. It might be different for different DB engines...but atleast in SQL Server, i do know that execution plan for triggers are cached just like SP's...so i dont really think that there is any real performance gain to be had by using SPs over triggers
InSane
ok, thank you... can you please help me how to create this in triggers?
@user335160 - About the query...you could write a single query combining all 5 using the UNION clause..but it might be preferable to do 1 by 1 because if u find a match in the first, then the other 4 dont even need to get executed at all
InSane
@user335160 - Check out the example http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx under the section `Use a trigger business rule between the employee and jobs tables`. It is very similar in syntax for everything that you need to do!!
InSane