Home >Database >Mysql Tutorial >How Can I Log the SQL Statements That Modify a Specific Table in SQL Server 2008?
Logging SQL that Affected a Table
To determine the source of updates to a column, you can create a trigger on the affected table that captures the SQL responsible for the changes. Let's explore how to achieve this in Microsoft SQL Server 2008.
Creating the Trigger
Utilizing a DDL statement, you can create a trigger that logs the SQL for table updates:
CREATE TRIGGER trigger_name ON table_name AFTER UPDATE AS BEGIN -- Declare a variable to store the executed SQL DECLARE @sql_text VARCHAR(MAX); -- Retrieve the executed SQL from the context_info() function SET @sql_text = CAST(EVENTDATA() AS NVARCHAR(MAX)); -- Insert the SQL text into a log table or perform other desired actions INSERT INTO log_table (sql_text) VALUES (@sql_text); END;
Accessing the Executed SQL
Once the trigger is created, the EVENTDATA() function can be used within the trigger code to capture the executed SQL. The EVENTDATA() function provides access to information about the current database event, including the SQL text that caused it. By extracting this information, you can identify the source of the column updates.
Additional Notes:
The above is the detailed content of How Can I Log the SQL Statements That Modify a Specific Table in SQL Server 2008?. For more information, please follow other related articles on the PHP Chinese website!