Goal: Create a table (Changes) to record any changes that take place within a db with the following information:
| Schema | Table | ColumnChanged | DeletedValue | InsertedValue |
|---|
When creating the triggers for this I want to make and utilize a function that will format the "inserted" and "deleted" tables (generated by SQL already upon triggering).
Question: Is there a way I can make this work with temporary tables or table variables. I have run into problems with both. Or if there is another solution I am open to suggestions.
So Far: I thought to create a function with input parameters @Schema and @Table that I can use on the 'inserted' and 'deleted' tables to get the required data to build my Changes table. The intent was to create temporary tables for each column with (ColumnName, Value) and stack them until the all columns were added. However, Temporary tables are not supported for use within functions in SQL Server. I, then planned to use table variables instead but have run into the issue of table variables not being within the scope when utilizing dynamic SQL. I need to use Dynamic SQL to select data from my function parameters (@Schema & @Table) because 'SELECT * FROM @Schema.@Table does not work.
Example Code:
DECLARE @Table nvarchar(max) = 'WireColor'
DECLARE @Schema nvarchar(max) = 'Enum'
DECLARE @tempTable TABLE (ColumnName varchar(max))
INSERT INTO @tempTable (ColumnName)
(SELECT Column_Name FROM INFORMATION_SCHEMA.Columns WHERE Table_Name = @Table AND TABLE_SCHEMA = @Schema)
SELECT * FROM (
SELECT Row_Number() OVER (ORDER BY (Select NULL) ) AS rownumber, *
FROM @tempTable) sub WHERE rownumber = 1
Will normally yield:
| rownumber| ColumnName |
| 1 | ID |
Using this within dynamic sql as follows:
DECLARE @Table nvarchar(max) = 'WireColor'
DECLARE @Schema nvarchar(max) = 'Enum'
DECLARE @tempTable TABLE (ColumnName varchar(max))
INSERT INTO @tempTable (ColumnName)
(SELECT Column_Name FROM INFORMATION_SCHEMA.Columns WHERE Table_Name = @Table AND TABLE_SCHEMA = @Schema)
DECLARE @sp_select nvarchar(max) = ('SELECT * FROM (
SELECT Row_Number() OVER (ORDER BY (Select NULL) ) AS rownumber, *
FROM @tempTable) sub WHERE rownumber = 1')
EXEC sp_executesql @sp_select
Results in the following error: Msg 1087, Level 15, State 2, Line 3 Must declare the table variable "@tempTable".