snippetMinor
How can we get table name from inside trigger?
Viewed 0 times
cantriggergetnamehowfromtableinside
Problem
I need to pass the table name from trigger to procedure.
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.
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)
ENDI 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.
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.:
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
GOA 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 @sqlCode 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
GOdeclare @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 @sqlContext
StackExchange Database Administrators Q#41301, answer score: 8
Revisions (0)
No revisions yet.