Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

SQL trigger, checking if table exists

Posted on 2010-09-02
4
Medium Priority
?
389 Views
Last Modified: 2012-06-22
This trigger does not work, but the query does. I need the trigger to check if the table exists if not, it will create it.
/****** Object:  DdlTrigger [trgMonitorChange]    Script Date: 06/03/2010 08:26:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create TRIGGER [trgMonitorChange]
ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
------------------------------
if exists(select * from tempdb.sys.tables where name ='##MonitorChange')
begin
--print 'Table ##MonitorChange does exists, record inserted.'
      set nocount on
      declare @EventType varchar(100)
      declare @SchemaName varchar(100)
      declare @ObjectName varchar(100)
      declare @ObjectType varchar(100)
      SELECT
       @EventType = EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]','nvarchar(max)')  
      ,@SchemaName = EVENTDATA().value('(/EVENT_INSTANCE/SchemaName)[1]','nvarchar(max)')  
      ,@ObjectName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(max)')
      ,@ObjectType = EVENTDATA().value('(/EVENT_INSTANCE/ObjectType)[1]','nvarchar(max)')  
      -- Is the default schema used
      if @SchemaName = ' ' select @SchemaName = default_schema_name from sys.sysusers u join sys.database_principals p
                                          on u.uid = p.principal_id  where u.name = CURRENT_USER
      insert into ##MonitorChange
              select @@servername,convert(varchar(100),DB_NAME()), @EventType, @SchemaName, @ObjectName, @ObjectType, getdate(), SUSER_SNAME(), CURRENT_USER, ORIGINAL_LOGIN()  
end
else
begin
--print 'Table ##MonitorChange does not exist, Table ##MontitorChange created, record inserted.'
      SET ANSI_NULLS ON
      SET QUOTED_IDENTIFIER ON
      SET ANSI_PADDING ON
      CREATE TABLE [dbo].[##MonitorChange](
            [Server_Name] [varchar](100) NULL,
            [DB_Name] [varchar](100) NULL,
            [EventType] [varchar](100) NULL,
            [SchemaName] [varchar](100) NULL,
            [ObjectName] [varchar](100) NULL,
            [ObjectType] [varchar](100) NULL,
            [EventDate] [datetime] NULL,
            [SystemUser] [varchar](100) NULL,
            [CurrentUser] [varchar](100) NULL,
            [OriginalUser] [varchar](100) NULL
      ) ON [PRIMARY]
      
      ------------------------------
      ------------------------------
--set nocount on
--declare @EventType1 varchar(100)
--declare @SchemaName1 varchar(100)
--declare @ObjectName1 varchar(100)
--declare @ObjectType1 varchar(100)
SELECT
 @EventType = EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]','nvarchar(max)')  
,@SchemaName = EVENTDATA().value('(/EVENT_INSTANCE/SchemaName)[1]','nvarchar(max)')  
,@ObjectName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(max)')
,@ObjectType = EVENTDATA().value('(/EVENT_INSTANCE/ObjectType)[1]','nvarchar(max)')  
-- Is the default schema used
if @SchemaName = ' ' select @SchemaName = default_schema_name from sys.sysusers u join sys.database_principals p
                        on u.uid = p.principal_id  where u.name = CURRENT_USER
insert into ##MonitorChange
      select @@servername,convert(varchar(100),DB_NAME()), @EventType, @SchemaName, @ObjectName, @ObjectType, getdate(), SUSER_SNAME(), CURRENT_USER, ORIGINAL_LOGIN()  
--SET ANSI_PADDING OFF      
end
go
------------------------------
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ENABLE TRIGGER [trgMonitorChange] ON DATABASE
0
Comment
Question by:asullivan62
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 

Author Comment

by:asullivan62
ID: 33590946
The table is never created if executed in a trigger.
0
 
LVL 5

Accepted Solution

by:
almander earned 2000 total points
ID: 33591719
Use

IF OBJECT_ID('tempdb..##MonitorChange'') IS NOT NULL

instead of

if exists(select * from tempdb.sys.tables where name ='##MonitorChange')
0
 

Author Closing Comment

by:asullivan62
ID: 33591998
Well I am not sure why that made the difference but it did and it works great now thanks.
0
 
LVL 5

Expert Comment

by:almander
ID: 33592316
For some crazy reason all flavors of temp tables are not stored in sys.tables, sysobjects, or information_schema.

The kicker is that ObjectId will work for any object. And also takes an optional parameter to specify the object type.

I.E.
OBJECT_ID('tempdb..##MonitorChange'', 'U')

http://msdn.microsoft.com/en-us/library/ms190324.aspx
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have written a PowerShell script to "walk" the security structure of each SQL instance to find:         Each Login (Windows or SQL)             * Its Server Roles             * Every database to which the login is mapped             * The associated "Database User" for this …
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

610 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question