Monday, March 19, 2012

how do I get the name of the table that fired a trigger?

I have a trigger set for INSERT conditions on a table and I want to use the table name in an argument within the trigger. Does anyone know of a way of obtaining that tablename that fired the trigger without having to hardcode it? (I want to be able to re-use the trigger code on various tables without having to alter it for each table)

Thanks

Colin

Here it is,

Code Snippet

Create table Main(i int)

Go

Create trigger main_trg on Main for insert

as

Declare @.TableName NVarchar(300)

Select

@.TableName = object_Name(parent_obj)

from

sysobjects where id=@.@.PROCID

Select @.TableName

Go

Insert Into main values(1)

|||Perfect - works like a charm.
2 questions though -
1. is there any significance to you using NVarchar(300) as the datatype?
2. Do you know the syntax needed to be able to use a variable like @.TableName in a select statement instead of hardcoding the table name?

Thanks again for your help.

Colin|||

1. Is there any significance to you using NVarchar(300) as the datatype?

Since the sql server objects are Unicode values, it always better to use the NVarchar datatype. Regarding Length I recommend to use 128. (sysname = Nvarchar(128)

2. Do you know the syntax needed to be able to use a variable like @.TableName in a select statement instead of hard coding the

You have to use the dynamic sql here,

Code Snippet

Exec(N'Select * From ' + @.TableName);

--or

Declare @.SQL as Nvarchar(4000);

Set @.SQL = N'Select * From ' + @.TableName

Exec sp_executesql @.SQL

|||OK, one last question!
What's the significance of the 'N' in EXEC(N'Select...... ?

Thanks|||

I think N come from Unicode

|||

Yes, exactly the regular ascii string will be enclosed in the single quote ‘.

To identify the Unicode values databases uses the N prefix.

No comments:

Post a Comment