简体   繁体   中英

SQL - Find all inserts in a stored procedure

long time listener, first time poster. I'm new to SQL and am trying to help another co-worker build some scripts to use with a testing tool. Our goal is to have something that can check a table against a set of criteria after an update to our application's code to make sure that the stored procedures are still generating expected data.

To that end (have I lost you yet?) I'm trying to find a way to find which tables and which columns in those tables are being updated by a given stored proc. I've found a script that can tell me what tables a stored procedure uses, but I can't find a way to also find what columns are used.

This is what I have for finding the tables:

WITH stored_procedures AS (
SELECT
o.name AS proc_name, oo.name AS table_name, d.resultobj AS updated,
ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
FROM sysdepends d 
INNER JOIN sysobjects o ON o.id=d.id
INNER JOIN sysobjects oo ON oo.id=d.depid
WHERE o.xtype = 'P' AND o.name = 'stored_procedure_here')
SELECT table_name FROM stored_procedures
WHERE row = 1 AND updated = 1 
ORDER BY proc_name,table_name 

Any ideas? Is this possible?

Thanks!

You could create something like a "protocol-table" who keeps track of all inserts beeing made. This protocol table would be filled by a Trigger wich will be executed every time you insert a row.

CREATE TRIGGER MyTrigger ON tableName /*Name of table which will have a protocol*/
FOR INSERT
AS

INSERT INTO protocol-table (protocol_id, tableName_id,nameOfTable, GETDATE()) /*protocol_id could be an auto-generated key*/
SELECT NULL, tableName.idField,'tableName', NULL                        /*tableName_id is the ID-Field of the table you protocol*/
FROM inserted /*inserted is a "logical table". Leave this the way it is */

GO

Each time an INSERT is made to your table the ID of this INSERT and the name of the table who was affected by this INSERT would appear in the protocol.

The downside of this: You would have to do this for every table you have to make sure everything gets protocolled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM