Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Problem using the INSERTED table in a Trigger

Author  Topic 

rebeccasmith
Starting Member

3 Posts

Posted - 2010-11-08 : 20:01:18
Hi,

I have a trigger on a table for update and i am trying to access the inserted table via an inner join but i am getting an error saying that its an invalid object name.

This only happens when using the inserted table within the sql string.

I have no problem accessing the inserted table by the inserted statement at the bottom of the trigger.

my code is below:



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[tr_test_update]
ON [dbo].[TBL_BACKUPTEST]
FOR UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @ObjName VARCHAR(100),
@TableName VARCHAR(100),
@Cols NVARCHAR(4000),
@sql NVARCHAR(MAX),
@Data NVARCHAR(MAX),
@ParmDefinition nvarchar(500),
@Outputparam varchar(MAX);
SET @TableName = 'TBL_BACKUPTEST'
SELECT @Cols =
(
SELECT '+''|''+CASE WHEN [' +c.name+ '] IS NULL THEN ''NULL'' ELSE CAST([' + c.name + '] AS VARCHAR(MAX)) END'
FROM DataFX.sys.columns c
WHERE c.[object_id] = object_Id(@TableName)
FOR XML PATH(''),TYPE
).value('.','VARCHAR(MAX)')

SET @sql = N'SELECT @Data = ' + @Cols + ' FROM ' +@TableName+ ' b JOIN inserted as i on i.ROWID = b.ROWID'
SET @ParmDefinition = N'@Data varchar(MAX) OUTPUT';

EXECUTE sp_executesql @sql, @ParmDefinition, @Data=@Outputparam OUTPUT;

-- Insert statements for trigger here
INSERT INTO dbo.TBL_BACKUP ([TABLE],[ACTION],ROWID,DATA)
SELECT 'TBL_BACKUPTEST' AS [TABLE],'UPDATE' AS [ACTION],ROWID,@Outputparam FROM INSERTED
END


It would be great if someone could shed some light on this as i'm really confused.

Thanks

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2010-11-08 : 20:38:00
I haven't tested it, but I assume that it is because the inserted table is out of scope in the dynamic sql.

It would be best to explain what you are trying to do so that someone can suggest an alternative.




CODO ERGO SUM
Go to Top of Page
   

- Advertisement -