HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How can we get table name from inside trigger?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
cantriggergetnamehowfromtableinside

Problem

I need to pass the table name from trigger to procedure.

ALTER TRIGGER [dbo].[Trg_ProjectCreation] 
   ON  [dbo].[Projects] 
   AFTER INSERT
AS 
BEGIN   
    SET NOCOUNT ON; 
 -- procedure call 
    exec Proc_Test @Tablename (not need to hardcode)
END


I want to know is there any way I can get table name from trigger itself. I need this to be dynamic because when the table's name changes I don't want to change my code.

Solution

This might not be the best approach to dealing for your problem, but it will certainly achieve the stated goal.

ALTER TRIGGER [dbo].[Trg_ProjectCreation] ON  [dbo].[Projects] 
   AFTER INSERT
AS 
BEGIN   
    SET NOCOUNT ON; 
    declare @TableName sysname
    select @tablename = object_schema_name(parent_id) + '.' + object_name(parent_id) 
    from sys.triggers where object_id = @@PROCID

    exec dbo.myProcedure @Tablename 
END
GO


A better option may be to change the way the trigger is created, and putting the name down manually (if it fits your scenario), for e.g.:

declare @tablename sysname, @sql nvarchar(max)
set @tablename = '[dbo].[myTableName]'
set @sql = 'ALTER TRIGGER [dbo].[Trg_ProjectCreation] ON  ' + @tablename + ' 
   AFTER INSERT
AS 
BEGIN   
    SET NOCOUNT ON; 
    exec dbo.myProcedure ' + @tablename + '
END
GO'
exec sp_executeSQL @sql

Code Snippets

ALTER TRIGGER [dbo].[Trg_ProjectCreation] ON  [dbo].[Projects] 
   AFTER INSERT
AS 
BEGIN   
    SET NOCOUNT ON; 
    declare @TableName sysname
    select @tablename = object_schema_name(parent_id) + '.' + object_name(parent_id) 
    from sys.triggers where object_id = @@PROCID

    exec dbo.myProcedure @Tablename 
END
GO
declare @tablename sysname, @sql nvarchar(max)
set @tablename = '[dbo].[myTableName]'
set @sql = 'ALTER TRIGGER [dbo].[Trg_ProjectCreation] ON  ' + @tablename + ' 
   AFTER INSERT
AS 
BEGIN   
    SET NOCOUNT ON; 
    exec dbo.myProcedure ' + @tablename + '
END
GO'
exec sp_executeSQL @sql

Context

StackExchange Database Administrators Q#41301, answer score: 8

Revisions (0)

No revisions yet.