I am looking for a good way to log changes that occur on a particular set of tables in my SQL Server 2005 database. I believe the best way to do this is through a trigger that get's executed on updates and deletes. Is there anyway to grab the actual statement that is being ran? Once I have the statement I can easily log it someplace else (other DB table). However, I have not found an easy way (if possible) to grab the SQL statement that is being ran.
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
You should be able to accomplish this using the system management views.
An example would be something like this:
I'm not sure this will be as useful to you as a more data-centric logging mechanism might be, though.
do you really need to log the statement that ran, most people log the changed data (INSERTED and DELETED tables within the trigger).
Use a Log Trigger
There is little reason to capture the actual SQL as there can many different statements that change data in the same way.
Triggers are bad, I'd stay away from triggers.
If you are trying to troubleshoot something, attach Sql Profiler to the database with specific conditions. This will log every query run for your inspection.
Another option is to change to calling program to log its queries. This is a very common practice.
MSSQL has virtual tables named 'Inserted' and 'Deleted', which contain newly-inserted and/or newly-deleted and/or newly-updated data records, which you can access from a trigger ... I use these, to know what data has changed (that's instead of being told what statement changed the data).