How to Find Table Space in SQL Server and in Oracle? - sql

I have to find the table space of the table.
I tried sp_spaceused 'MyTableName'
But it is not Working. Are there any other ways?

In Oracle the tablespace name is contained in the dba_tables view.
select owner, tablespace_name
from dba_tables
where table_name = 'MyTableName'
Alternatively you can use the user_tables view to see the table name and TS name of only tables the current schema contains.
select table_name, tablespace_name
from user_tables
where table_name = 'MyTableName'

This should work fine for you As it works for me.
Solution refered from: How to find the total tablespace usage in SQL Server 2008? by Oleg Dok
set nocount on
declare #indexes table(
QualifiedName nvarchar(512),
IndexId int,
FGName nvarchar(128),
Type nvarchar(50),
NumKeys int,
IndexKB numeric(28,0),
UsedKB numeric(28,0),
FreeKB numeric(28,0),
Rows numeric(28,0),
RowModCtr numeric(28,0),
OrigFillFactor int,
tableid bigint
)
insert into #indexes
select
db_name() + '.' + isnull(su.name,'<unknown-user>') + '.' + so.name + '.' + isnull(i.name,'<Heap>') QualifiedName,
i.index_id IndexId,
(select isnull(name,'') from sys.filegroups where data_space_id = i.data_space_id) FGName,
case
when so.type = 'V' then 'Indexed View: '
else ''
end +
case
when i.index_id = 0 then 'Heap'
when i.index_id = 1 then 'Clustered'
else 'Non Clustered'
end Type,
0 NumKeys,
a.used_pages* 8 IndexKB,
CASE
When a.type <> 1 Then a.used_pages * 8
When p.index_id < 2 Then a.data_pages * 8
Else 0
END UsedKB,
(a.total_pages-a.used_pages)* 8 FreeKB,
p.rows Rows,
0 RowModCtr,
i.fill_factor OrigFillFactor,
convert(bigint,db_id()) * power(convert(bigint,2),48) + convert(bigint,su.schema_id) * power(convert(bigint,2),32) + so.object_id tableid
from
sys.objects so with (readpast)
inner join sys.schemas su with (readpast) on su.schema_id = so.schema_id
inner join sys.indexes i with (readpast) on so.object_id = i.object_id
inner join sys.partitions p with (readpast) ON i.object_id = p.object_id and i.index_id = p.index_id
inner join sys.allocation_units a with (readpast) on p.partition_id = a.container_id
where
(so.type = 'U') and a.type_Desc = 'IN_ROW_DATA'
and isnull(INDEXPROPERTY(i.object_id, i.name, 'IsStatistics'),0) = 0
and isnull(INDEXPROPERTY(i.object_id, i.name, 'IsAutoStatistics'),0) = 0
and isnull(INDEXPROPERTY(i.object_id, i.name, 'IsHypothetical'),0) = 0
order by
IndexKB desc
select
i.QualifiedName,
i.IndexId,
i.FGName,
i.Type,
i.NumKeys,
i.IndexKB,
(i.UsedKB - isnull(t.s_UsedKB,0)) UsedKB,
(i.FreeKB - isnull(t.s_FreeKB,0)) FreeKB,
i.Rows,
i.RowModCtr,
i.OrigFillFactor
from
#indexes i
left outer join (
select tableid, sum(UsedKB) s_UsedKB, sum(FreeKB) s_FreeKB
from #indexes
where IndexId > 1
group by tableid
) t on t.tableid = i.tableid
and i.IndexId <= 1
order by
IndexKB desc

Related

TSQL / SQL-SERVER: How to find all tables in a snapshot replication that have primary keys

I've been tasked with moving all tables in a single snapshot replication that have primary keys to the transaction replication. We get vendor updates and they may have added keys to tables that were in the Snapshot replication.
I've tried to break it down into 2 steps, finding all tables in a snapshot replication, and then checking to see if those tables have a primary key.
I've tried to piece together a few different code samples, but I may need to start over, here's what I've got so far.
--=============================================================================================
SELECT DB_NAME () PublisherDB
, sp.name AS PublisherName
, sa.name AS TableName
, UPPER (srv.srvname) AS SubscriberServerName
,*
FROM dbo.syspublications sp
JOIN dbo.sysarticles sa ON sp.pubid = sa.pubid
JOIN dbo.syssubscriptions s ON sa.artid = s.artid
JOIN master.dbo.sysservers srv ON s.srvid = srv.srvid;
--=============================================================================================
SELECT DB_NAME () AS db
, SCHEMA_NAME (o.schema_id) AS [Schema]
, so.name AS table_name
, so.type
, CASE WHEN TABLE_NAME IN (
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
) THEN 1 ELSE 0 END AS HasPrimaryKey
--INTO #t2
FROM sys.objects o WITH (NOLOCK)
INNER JOIN sysobjects so WITH (NOLOCK)
--INNER JOIN #t1 ON t1.
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS t2 ON t2.TABLE_NAME = so.name ON so.id = o.object_id
WHERE (
(so.xtype = 'U') -- user table xtype: learn.microsoft.com/en-us/sql/relational-databases/system-compatibility-views/sys-sysobjects-transact-sql?view=sql-server-ver15
OR (so.xtype = 'V') -- view
OR (so.xtype = 'P') -- stored procedure
)
AND so.category <> 2
AND so.name IN (
SELECT DISTINCT OBJECT_NAME (objid) FROM dbo.sysarticles
)
ORDER BY so.name
, so.type;
--=============================================================================================
DECLARE #jobId UNIQUEIDENTIFIER;
DECLARE #jobName sysname;
SELECT #jobId = jobs.job_id
, #jobName = jobs.name
FROM msdb.dbo.sysjobs jobs (NOLOCK)
JOIN msdb.dbo.syscategories categories (NOLOCK) ON jobs.category_id = categories.category_id
WHERE categories.name = 'REPL-Snapshot'
AND jobs.name LIKE '%db-name%';
SELECT #jobId
, #jobName;
EXEC sp_start_job #job_id = #jobId;
This is what I ended up going with. I pieced together and tweaked various snippets of code I've found.
Some from here: https://dataedo.com/kb/query/sql-server/list-tables-with-their-primary-keys
Other code from here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/50c6890b-8dc1-46c6-aeda-d97149a9692f/list-all-replicated-tables-and-their-destination?forum=sqlreplication
--====================================================================================================================================================
-- Get tables in Snapshot replication for the selected DB.
--====================================================================================================================================================
IF OBJECT_ID ('tempdb..#t1') IS NOT NULL DROP TABLE #t1;
SELECT pub.name AS [Publication]
, CASE WHEN pub.name LIKE '%Snapshot%' THEN 'SnapShot'
WHEN pub.name LIKE '%Transaction%' THEN 'Transaction' ELSE NULL END AS ReplicationType
, art.name AS [Article]
, serv.name AS [Subsriber]
, sub.dest_db AS [DestinationDB]
, obj.object_id
, CASE WHEN obj.type = 'U' THEN 'Table'
WHEN obj.type = 'V' THEN 'View'
WHEN obj.type = 'P' THEN 'SP' ELSE NULL END AS ObjectType
INTO #t1
FROM dbo.syssubscriptions sub
INNER JOIN sys.servers serv ON serv.server_id = sub.srvid
INNER JOIN dbo.sysarticles art ON art.artid = sub.artid
INNER JOIN dbo.syspublications pub ON pub.pubid = art.pubid
INNER JOIN sys.objects obj ON obj.object_id = art.objid
WHERE CASE WHEN pub.name LIKE '%Snapshot%' THEN 'SnapShot'
WHEN pub.name LIKE '%Transaction%' THEN 'Transaction' ELSE NULL END = 'Snapshot';
--====================================================================================================================================================
-- Check for primary keys on the above tables
--====================================================================================================================================================
SELECT SCHEMA_NAME (tab.schema_id) AS [schema_name]
, tab.[name] AS table_name
, pk.[name] AS pk_name
, SUBSTRING (column_names, 1, LEN (column_names) - 1) AS [columns]
FROM sys.tables tab
LEFT OUTER JOIN sys.indexes pk ON tab.object_id = pk.object_id
AND pk.is_primary_key = 1
CROSS APPLY (
SELECT col.[name] + ', '
FROM sys.index_columns ic
INNER JOIN sys.columns col ON ic.object_id = col.object_id
AND ic.column_id = col.column_id
WHERE ic.object_id = tab.object_id
AND ic.index_id = pk.index_id
ORDER BY col.column_id
FOR XML PATH ('')
) D(column_names)
WHERE pk.object_id IN (
SELECT object_id FROM #t1
)
ORDER BY SCHEMA_NAME (tab.schema_id)
, tab.[name];

Get all tables from database, if the table has some records present

Is there any way to get all the tables, with a condition that if table is not empty(if it has some records present).
I can get the list of tables with :
USE 'DatabaseName'
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_Schema = 'dbo'
ORDER BY table_NAME.
But, I want something like
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_Schema = 'dbo'
AND "**table has some records present**" ORDER BY table_NAME
Try :
SELECT
OBJECT_NAME(T.OBJECT_ID) AS TABLE_NAME,
SUM(P.ROWS) AS TOTAL_ROWS
FROM
sys.tables T
INNER JOIN
sys.partitions P
ON T.OBJECT_ID = P.OBJECT_ID
WHERE
P.INDEX_ID IN (0,1)
GROUP BY
T.OBJECT_ID
HAVING
SUM(P.ROWS) > 0
run this
select 'select count(*) [entries],'''+ TABLE_NAME + ''' from '+ quotename(TABLE_SCHEMA) + '.' + quotename(TABLE_NAME) + ' union' from INFORMATION_SCHEMA.TABLES
to get a list of every table and the number of entries in that table then you can put that into a temp table and look for anything where entries >1.
Remember to remove the union at the end.
select * from
(
SELECT sc.name +'.'+ ta.name TableName
,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
) as T where RowCnt>0
More help can get you from here

Get index statistics information for tables referenced in a specific view

I'm trying to amend the following script to point at just the indexes associated with a particular view vw_foo. Is this possible?
SELECT name AS index_name,
STATS_DATE(OBJECT_ID, index_id) AS StatsUpdated
FROM sys.indexes
Edit
When I say "associated" I mean the indexes on the underlying tables that are used to create the view
Possibly, it will be helpful for you -
SELECT
SCHEMA_NAME(o.[schema_id]) + '.' + o.name
, s.name
, statistics_update_date = STATS_DATE(o.[object_id], stats_id)
FROM sys.objects o
JOIN sys.stats s ON o.[object_id] = s.[object_id]
WHERE o.[type] = 'V' AND o.name = 'vw_foo'
DECLARE #table_name SYSNAME
SELECT #table_name = 'dbo.vw_foo'
EDITED
When I say "associated" I mean the indexes on the tables that are used
by the view
This query returns the list of the views where is used the specified table + shows additional info about the used index -
SELECT
o.table_name
, b.view_name
, i.name
, stast_updates = STATS_DATE(i.[object_id], i.index_id)
, dm_ius.last_user_seek
, dm_ius.last_user_scan
, dm_ius.last_user_lookup
, dm_ius.last_user_update
, dm_ius.user_updates
, dm_ius.user_lookups
, dm_ius.user_scans
, dm_ius.user_seeks
FROM (
SELECT
table_name = s.name + '.' + o.name
, o.[object_id]
FROM sys.objects o
JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
WHERE o.[type] = 'U'
AND s.name + '.' + o.name = #table_name
) o
JOIN sys.indexes i ON o.[object_id] = i.[object_id]
AND i.[type] > 0
AND i.is_disabled = 0
AND i.is_hypothetical = 0
LEFT JOIN sys.dm_db_index_usage_stats dm_ius ON i.index_id = dm_ius.index_id AND dm_ius.[object_id] = i.[object_id]
OUTER APPLY (
SELECT
view_name = r.referencing_schema_name + '.' + r.referencing_entity_name
, r.referencing_id
FROM sys.dm_sql_referencing_entities (o.table_name, 'OBJECT') r
JOIN sys.objects o2 ON r.referencing_id = o2.[object_id]
WHERE o2.[type] = 'V'
) b
WHERE b.view_name IS NOT NULL
The existing answers were probably heading towards checking the name in sys.objects but never do it. But there's no need to do so anyway, since the OBJECT_ID() function lets you get an object_id in a clean fashion:
SELECT name AS index_name,
STATS_DATE(OBJECT_ID, index_id) AS StatsUpdated
FROM sys.indexes
WHERE object_id = OBJECT_ID('vw_foo')

How to find the total tablespace usage in SQL Server 2008?

In SQL-server 2008, How would I find (through an SQL query), the percentage of tablespace usage for a particular instance(or all instances) of a SQL Server(2008 R2)?
Also, what is the best way (query) to get the list of all the Named Instances of a SQL Server?
is this what you need:
EXEC sp_spaceused null, false
result:
database_name database_size unallocated space
--------------- ------------------ ------------------
DATABASE_NAME 220.25 MB 69.92 MB
reserved data index_size unused
------------------ ------------------ ------------------ ------------------
110672 KB 80368 KB 26944 KB 3360 KB
Use the script:
set nocount on
declare #indexes table(
QualifiedName nvarchar(512),
IndexId int,
FGName nvarchar(128),
Type nvarchar(50),
NumKeys int,
IndexKB numeric(28,0),
UsedKB numeric(28,0),
FreeKB numeric(28,0),
Rows numeric(28,0),
RowModCtr numeric(28,0),
OrigFillFactor int,
tableid bigint
)
insert into #indexes
select
db_name() + '.' + isnull(su.name,'<unknown-user>') + '.' + so.name + '.' + isnull(i.name,'<Heap>') QualifiedName,
i.index_id IndexId,
(select isnull(name,'') from sys.filegroups where data_space_id = i.data_space_id) FGName,
case
when so.type = 'V' then 'Indexed View: '
else ''
end +
case
when i.index_id = 0 then 'Heap'
when i.index_id = 1 then 'Clustered'
else 'Non Clustered'
end Type,
0 NumKeys,
a.used_pages* 8 IndexKB,
CASE
When a.type <> 1 Then a.used_pages * 8
When p.index_id < 2 Then a.data_pages * 8
Else 0
END UsedKB,
(a.total_pages-a.used_pages)* 8 FreeKB,
p.rows Rows,
0 RowModCtr,
i.fill_factor OrigFillFactor,
convert(bigint,db_id()) * power(convert(bigint,2),48) + convert(bigint,su.schema_id) * power(convert(bigint,2),32) + so.object_id tableid
from
sys.objects so with (readpast)
inner join sys.schemas su with (readpast) on su.schema_id = so.schema_id
inner join sys.indexes i with (readpast) on so.object_id = i.object_id
inner join sys.partitions p with (readpast) ON i.object_id = p.object_id and i.index_id = p.index_id
inner join sys.allocation_units a with (readpast) on p.partition_id = a.container_id
where
(so.type = 'U') and a.type_Desc = 'IN_ROW_DATA'
and isnull(INDEXPROPERTY(i.object_id, i.name, 'IsStatistics'),0) = 0
and isnull(INDEXPROPERTY(i.object_id, i.name, 'IsAutoStatistics'),0) = 0
and isnull(INDEXPROPERTY(i.object_id, i.name, 'IsHypothetical'),0) = 0
order by
IndexKB desc
select
i.QualifiedName,
i.IndexId,
i.FGName,
i.Type,
i.NumKeys,
i.IndexKB,
(i.UsedKB - isnull(t.s_UsedKB,0)) UsedKB,
(i.FreeKB - isnull(t.s_FreeKB,0)) FreeKB,
i.Rows,
i.RowModCtr,
i.OrigFillFactor
from
#indexes i
left outer join (
select tableid, sum(UsedKB) s_UsedKB, sum(FreeKB) s_FreeKB
from #indexes
where IndexId > 1
group by tableid
) t on t.tableid = i.tableid
and i.IndexId <= 1
order by
IndexKB desc

Need to list all triggers in SQL Server database with table name and table's schema

I need to list all triggers in SQL Server database with table name and table's schema.
I'm almost there with this:
SELECT trigger_name = name, trigger_owner = USER_NAME(uid),table_schema = , table_name = OBJECT_NAME(parent_obj),
isupdate = OBJECTPROPERTY( id, 'ExecIsUpdateTrigger'), isdelete = OBJECTPROPERTY( id, 'ExecIsDeleteTrigger'),
isinsert = OBJECTPROPERTY( id, 'ExecIsInsertTrigger'), isafter = OBJECTPROPERTY( id, 'ExecIsAfterTrigger'),
isinsteadof = OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger'),
[disabled] = OBJECTPROPERTY(id, 'ExecIsTriggerDisabled')
FROM sysobjects INNER JOIN sysusers ON sysobjects.uid = sysusers.uid
WHERE type = 'TR'
I just need to get the table's schema also.
Here's one way:
SELECT
sysobjects.name AS trigger_name
,USER_NAME(sysobjects.uid) AS trigger_owner
,s.name AS table_schema
,OBJECT_NAME(parent_obj) AS table_name
,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
INNER JOIN sysusers
ON sysobjects.uid = sysusers.uid
INNER JOIN sys.tables t
ON sysobjects.parent_obj = t.object_id
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'
EDIT:
Commented out join to sysusers for query to work on AdventureWorks2008.
SELECT
sysobjects.name AS trigger_name
,USER_NAME(sysobjects.uid) AS trigger_owner
,s.name AS table_schema
,OBJECT_NAME(parent_obj) AS table_name
,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
/*
INNER JOIN sysusers
ON sysobjects.uid = sysusers.uid
*/
INNER JOIN sys.tables t
ON sysobjects.parent_obj = t.object_id
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'
EDIT 2: For SQL 2000
SELECT
o.name AS trigger_name
,'x' AS trigger_owner
/*USER_NAME(o.uid)*/
,s.name AS table_schema
,OBJECT_NAME(o.parent_obj) AS table_name
,OBJECTPROPERTY(o.id, 'ExecIsUpdateTrigger') AS isupdate
,OBJECTPROPERTY(o.id, 'ExecIsDeleteTrigger') AS isdelete
,OBJECTPROPERTY(o.id, 'ExecIsInsertTrigger') AS isinsert
,OBJECTPROPERTY(o.id, 'ExecIsAfterTrigger') AS isafter
,OBJECTPROPERTY(o.id, 'ExecIsInsteadOfTrigger') AS isinsteadof
,OBJECTPROPERTY(o.id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects AS o
/*
INNER JOIN sysusers
ON sysobjects.uid = sysusers.uid
*/
INNER JOIN sysobjects AS o2
ON o.parent_obj = o2.id
INNER JOIN sysusers AS s
ON o2.uid = s.uid
WHERE o.type = 'TR'
Here you go.
SELECT
[so].[name] AS [trigger_name],
USER_NAME([so].[uid]) AS [trigger_owner],
USER_NAME([so2].[uid]) AS [table_schema],
OBJECT_NAME([so].[parent_obj]) AS [table_name],
OBJECTPROPERTY( [so].[id], 'ExecIsUpdateTrigger') AS [isupdate],
OBJECTPROPERTY( [so].[id], 'ExecIsDeleteTrigger') AS [isdelete],
OBJECTPROPERTY( [so].[id], 'ExecIsInsertTrigger') AS [isinsert],
OBJECTPROPERTY( [so].[id], 'ExecIsAfterTrigger') AS [isafter],
OBJECTPROPERTY( [so].[id], 'ExecIsInsteadOfTrigger') AS [isinsteadof],
OBJECTPROPERTY([so].[id], 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects AS [so]
INNER JOIN sysobjects AS so2 ON so.parent_obj = so2.Id
WHERE [so].[type] = 'TR'
A couple of things here...
Also I see that you were attempting to pull the parent tables schema information, I believe in order to do so you would also need to join the sysobjects table on itself so that you can correctly get the schema information for the parent table. the query above does this. Also the sysusers table wasn't needed in the results so that Join has been removed.
tested with SQL 2000, SQL 2005, and SQL 2008 R2
You can also get the body of triggers as following:
SELECT o.[name],
c.[text]
FROM sys.objects AS o
INNER JOIN sys.syscomments AS c
ON o.object_id = c.id
WHERE o.[type] = 'TR'
I had the same task recently and I used the following for sql server 2012 db. Use management studio and connect to the database you want to search. Then execute the following script.
Select
[tgr].[name] as [trigger name],
[tbl].[name] as [table name]
from sysobjects tgr
join sysobjects tbl
on tgr.parent_obj = tbl.id
WHERE tgr.xtype = 'TR'
SELECT
ServerName = ##servername,
DatabaseName = db_name(),
SchemaName = isnull( s.name, '' ),
TableName = isnull( o.name, 'DDL Trigger' ),
TriggerName = t.name,
Defininion = object_definition( t.object_id )
FROM sys.triggers t
LEFT JOIN sys.all_objects o
ON t.parent_id = o.object_id
LEFT JOIN sys.schemas s
ON s.schema_id = o.schema_id
ORDER BY
SchemaName,
TableName,
TriggerName
Use this query :
SELECT OBJECT_NAME(parent_id) as Table_Name, * FROM [Database_Name].sys.triggers
It's simple and useful.
And what do you think about this: Very short and neat :)
SELECT OBJECT_NAME(parent_id) Table_or_ViewNM,
name TriggerNM,
is_instead_of_trigger,
is_disabled
FROM sys.triggers
WHERE parent_class_desc = 'OBJECT_OR_COLUMN'
ORDER BY OBJECT_NAME(parent_id),
Name ;
SELECT
sysobjects.name AS trigger_name ,OBJECT_NAME(parent_obj) AS table_name ,s.name AS table_schema
,USER_NAME(sysobjects.uid) AS trigger_owner
,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
INNER JOIN sysusers
ON sysobjects.uid = sysusers.uid
INNER JOIN sys.tables t
ON sysobjects.parent_obj = t.object_id
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'
this working for me
This is what I use (usually wrapped in something I stuff in Model):
Select
[Parent] = Left((Case When Tr.Parent_Class = 0 Then '(Database)' Else Object_Name(Tr.Parent_ID) End), 32),
[Schema] = Left(Coalesce(Object_Schema_Name(Tr.Object_ID), '(None)'), 16),
[Trigger name] = Left(Tr.Name, 32),
[Type] = Left(Tr.Type_Desc, 3), -- SQL or CLR
[MS?] = (Case When Tr.Is_MS_Shipped = 1 Then 'X' Else ' ' End),
[On?] = (Case When Tr.Is_Disabled = 0 Then 'X' Else ' ' End),
[Repl?] = (Case When Tr.Is_Not_For_Replication = 0 Then 'X' Else ' ' End),
[Event] = Left((Case When Tr.Parent_Class = 0
Then (Select Top 1 Left(Te.Event_Group_Type_Desc, 40)
From Sys.Trigger_Events As Te
Where Te.Object_ID = Tr.Object_ID)
Else ((Case When Tr.Is_Instead_Of_Trigger = 1 Then 'Instead Of ' Else 'After ' End)) +
SubString(Cast((Select [text()] = ', ' + Left(Te.Type_Desc, 1) + Lower(SubString(Te.Type_Desc, 2, 32)) +
(Case When Te.Is_First = 1 Then ' (First)' When Te.Is_Last = 1 Then ' (Last)' Else '' End)
From Sys.Trigger_Events As Te
Where Te.Object_ID = Tr.Object_ID
Order By Te.[Type]
For Xml Path ('')) As Character Varying), 3, 60) End), 60)
-- If you like:
-- , [Get text with] = 'Select Object_Definition(' + Cast(Tr.Object_ID As Character Varying) + ')'
From
Sys.Triggers As Tr
Order By
Tr.Parent_Class, -- database triggers first
Parent -- alphabetically by parent
As you see it is a skosh more McGyver, but I think it's worth it:
Parent Schema Trigger name Type MS? On? Repl? Event
-------------------------------- ---------------- -------------------------------- ---- ---- ---- ----- -----------------------------------------
(Database) (None) ddlDatabaseTriggerLog SQL X DDL_DATABASE_LEVEL_EVENTS
Employee HumanResources dEmployee SQL X Instead Of Delete
Person Person iuPerson SQL X After Insert, Update
PurchaseOrderDetail Purchasing iPurchaseOrderDetail SQL X X After Insert
PurchaseOrderDetail Purchasing uPurchaseOrderDetail SQL X X After Update
PurchaseOrderHeader Purchasing uPurchaseOrderHeader SQL X X After Update
SalesOrderDetail Sales iduSalesOrderDetail SQL X X After Insert, Update, Delete
SalesOrderHeader Sales uSalesOrderHeader SQL X After Update (First)
Vendor Purchasing dVendor SQL X Instead Of Delete
WorkOrder Production iWorkOrder SQL X X After Insert
WorkOrder Production uWorkOrder SQL X X After Update
(Scroll right to see the final and most useful column)
Use This Query :
SELECT
DB_NAME() AS DataBaseName,
S.Name AS SchemaName,
T.name AS TableName,
dbo.SysObjects.Name AS TriggerName,
dbo.sysComments.Text AS SqlContent,
FROM dbo.SysObjects
INNER JOIN dbo.sysComments ON dbo.SysObjects.ID = dbo.sysComments.ID
INNER JOIN sys.tables AS T ON sysobjects.parent_obj = t.object_id
INNER JOIN sys.schemas AS S ON t.schema_id = s.schema_id
WHERE dbo.SysObjects.xType = 'TR'
AND dbo.SysObjects.Name LIKE 'Permit_AfterInsert' ---- <----- HERE
this may help.
SELECT DISTINCT o.[name] AS [Table]
FROM [sysobjects] o
JOIN [sysobjects] tr
ON o.[id] = tr.[parent_obj]
WHERE tr.[type] = 'tr'
ORDER BY [Table]
Get a list of tables and all their triggers.
SELECT DISTINCT o.[name] AS [Table], tr.[name] AS [Trigger]
FROM [sysobjects] o
JOIN [sysobjects] tr
ON o.[id] = tr.[parent_obj]
WHERE tr.[type] = 'tr'
ORDER BY [Table], [Trigger]
The just above code is incorrect as shown:
SELECT
sysobjects.name AS trigger_name
--,USER_NAME(sysobjects.uid) AS trigger_owner
--,s.name AS table_schema
--,OBJECT_NAME(parent_obj) AS table_name
--,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
--,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
--,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
--,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
--,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
--,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
/*
INNER JOIN sysusers
ON sysobjects.uid = sysusers.uid
*/
INNER JOIN sys.tables t
ON sysobjects.parent_obj = t.object_id
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'
EXCEPT
SELECT OBJECT_NAME(parent_id) as Table_Name FROM sys.triggers
C# Cribs: I ended up with this super generic one liner. Hope this is useful to both the original poster and/or people who just typed the same question I did into Google:
SELECT TriggerRecord.name as TriggerName,ParentRecord.name as ForTableName
FROM sysobjects TriggerRecord
INNER JOIN sysobjects ParentRecord ON TriggerRecord.parent_obj=ParentRecord.id
WHERE TriggerRecord.xtype='TR'
Query Characteristics:
Usable with any SQL database (i.e. Initial Catalog)
Self explanatory
One single statement
Pasteable directly into most IDE's for most languages
Necromancing.
Just posting because all solutions so far fall a bit short of completeness.
SELECT
sch.name AS trigger_table_schema
,systbl.name AS trigger_table_name
,systrg.name AS trigger_name
,sysm.definition AS trigger_definition
,systrg.is_instead_of_trigger
-- https://stackoverflow.com/questions/5340638/difference-between-a-for-and-after-triggers
-- Difference between a FOR and AFTER triggers?
-- CREATE TRIGGER trgTable on dbo.Table FOR INSERT,UPDATE,DELETE
-- Is the same as
-- CREATE TRIGGER trgTable on dbo.Table AFTER INSERT,UPDATE,DELETE
-- An INSTEAD OF trigger is different, and fires before and instead of the insert
-- and can be used on views, in order to insert the appropriate values into the underlying tables.
-- AFTER specifies that the DML trigger is fired only when all operations
-- specified in the triggering SQL statement have executed successfully.
-- All referential cascade actions and constraint checks also must succeed before this trigger fires.
-- AFTER is the default when FOR is the only keyword specified.
,CASE WHEN systrg.is_instead_of_trigger = 1 THEN 0 ELSE 1 END AS is_after_trigger
,systrg.is_not_for_replication
,systrg.is_disabled
,systrg.create_date
,systrg.modify_date
,CASE WHEN systrg.parent_class = 1 THEN 'TABLE' WHEN systrg.parent_class = 0 THEN 'DATABASE' END trigger_class
,CASE
WHEN systrg.[type] = 'TA' then 'Assembly (CLR) trigger'
WHEN systrg.[type] = 'TR' then 'SQL trigger'
ELSE ''
END AS trigger_type
-- https://dataedo.com/kb/query/sql-server/list-triggers
-- ,(CASE WHEN objectproperty(systrg.object_id, 'ExecIsUpdateTrigger') = 1
-- THEN 'UPDATE ' ELSE '' END
-- + CASE WHEN objectproperty(systrg.object_id, 'ExecIsDeleteTrigger') = 1
-- THEN 'DELETE ' ELSE '' END
-- + CASE WHEN objectproperty(systrg.object_id, 'ExecIsInsertTrigger') = 1
-- THEN 'INSERT' ELSE '' END
-- ) AS trigger_event
,
(
STUFF
(
(
SELECT
', ' + type_desc AS [text()]
-- STRING_AGG(type_desc, ', ') AS foo
FROM sys.events AS syse
WHERE syse.object_id = systrg.object_id
FOR XML PATH(''), TYPE
-- GROUP BY syse.object_id
).value('.[1]', 'nvarchar(MAX)')
, 1, 2, ''
)
) AS trigger_event_groups
-- ,CASE WHEN systrg.parent_class = 1 THEN 'TABLE' WHEN systrg.parent_class = 0 THEN 'DATABASE' END trigger_class
,'DROP TRIGGER "' + sch.name + '"."' + systrg.name + '"; ' AS sql
-- ,systrg.*
FROM sys.triggers AS systrg
LEFT JOIN sys.sql_modules AS sysm
ON sysm.object_id = systrg.object_id
-- sys.objects for view triggers
-- LEFT JOIN sys.objects AS systbl ON systbl.object_id = systrg.object_id
-- inner join if you only want table-triggers
LEFT JOIN sys.tables AS systbl ON systbl.object_id = systrg.parent_id
LEFT JOIN sys.schemas AS sch
ON sch.schema_id = systbl.schema_id
WHERE (1=1)
-- AND sch.name IS NOT NULL
-- AND sch.name IS NULL
-- AND sch.name = 'dbo'
-- And here, exclude some triggers with a certain naming schema
/*
AND
(
-- systbl.name IS NULL
-- OR
NOT
(
systrg.name = 'TRG_' + systbl.name + '_INSERT_History'
OR
systrg.name = 'TRG_' + systbl.name + '_UPDATE_History'
OR
systrg.name = 'TRG_' + systbl.name + '_DELETE_History'
)
)
*/
ORDER BY
sch.name
,systbl.name
,systrg.name
If you are looking for ALL triggers, remember MS-SQL has both SQL-based triggers (sysobjects.type = 'TR') and CLR-based triggers (sysobjects.type = 'TA').
No need to join with other tables... all info can be obtained from sys.objects.
SELECT name as trigger_name
, object_name(parent_obj) as tableName
, object_schema_name(parent_obj) as schemaName
,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects s
WHERE s.type = 'TR'
SELECT tbl.name as Table_Name,trig.name as Trigger_Name,trig.is_disabled
FROM [sys].[triggers] as trig inner join sys.tables as tbl on
trig.parent_id = tbl.object_id
CREATE TABLE [dbo].[VERSIONS](
[ID] [uniqueidentifier] NOT NULL,
[DATE] [varchar](100) NULL,
[SERVER] [varchar](100) NULL,
[DATABASE] [varchar](100) NULL,
[USER] [varchar](100) NULL,
[OBJECT] [varchar](100) NULL,
[ACTION] [varchar](100) NULL,
[CODE] [varchar](max) NULL,
CONSTRAINT [PK_VERSIONS] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[VERSIONS] ADD CONSTRAINT [DF_VERSIONS_ID] DEFAULT (newid()) FOR [ID]
GO
DROP TRIGGER [DB_VERSIONS_TRIGGER] ON ALL SERVER
CREATE TRIGGER [DB_VERSIONS_TRIGGER] ON ALL SERVER FOR CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE,
CREATE_TRIGGER, ALTER_TRIGGER, DROP_TRIGGER, CREATE_FUNCTION, ALTER_FUNCTION, DROP_FUNCTION, CREATE_VIEW, ALTER_VIEW,
DROP_VIEW, CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS
SET NOCOUNT ON SET XACT_ABORT OFF;
BEGIN
TRY
DECLARE #DATA XML = EVENTDATA()
DECLARE #SERVER VARCHAR(100) = #DATA.value('(EVENT_INSTANCE/ServerName)[1]','VARCHAR(100)')
DECLARE #DATABASE VARCHAR(100) = #DATA.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'VARCHAR(100)')
DECLARE #USER VARCHAR(100) = #DATA.value('(/EVENT_INSTANCE/LoginName)[1]','VARCHAR(100)')
DECLARE #OBJECT VARCHAR(100) = #DATA.value('(EVENT_INSTANCE/ObjectName)[1]','VARCHAR(100)')
DECLARE #ACTION VARCHAR(100) = #DATA.value('(/EVENT_INSTANCE/EventType)[1]','VARCHAR(100)')
DECLARE #CODE VARCHAR(MAX) = #DATA.value('(/EVENT_INSTANCE//TSQLCommand)[1]','VARCHAR(MAX)' )
IF OBJECT_ID('DB_VERSIONS.dbo.VERSIONS') IS NOT NULL
BEGIN
INSERT INTO [DB_VERSIONS].[dbo].[VERSIONS]([SERVER], [DATABASE], [USER], [OBJECT], [ACTION], [DATE], [CODE]) VALUES (#SERVER, #DATABASE, #USER, #OBJECT, #ACTION, getdate(), ISNULL(#CODE, 'NA'))
END
END
TRY
BEGIN
CATCH
END
CATCH
RETURN
SELECT
OBJECT_NAME(PARENT_OBJECT_ID) AS PARENT_TABLE,
OBJECT_NAME(OBJECT_ID) TRIGGER_TABLE,
*
FROM
SYS.OBJECTS
WHERE TYPE = 'TR'
One difficulty is that the text, or description has line feeds. My clumsy kludge, to get it in something more tabular, is to add an HTML literal to the SELECT clause, copy and paste everything to notepad, save with an html extension, open in a browser, then copy and paste to a spreadsheet.
example
SELECT obj.NAME AS TBL,trg.name,sm.definition,'<br>'
FROM SYS.OBJECTS obj
LEFT JOIN (SELECT trg1.object_id,trg1.parent_object_id,trg1.name FROM sys.objects trg1 WHERE trg1.type='tr' AND trg1.name like 'update%') trg
ON obj.object_id=trg.parent_object_id
LEFT JOIN (SELECT sm1.object_id,sm1.definition FROM sys.sql_modules sm1 where sm1.definition like '%suser_sname()%') sm ON trg.object_id=sm.object_id
WHERE obj.type='u'
ORDER BY obj.name;
you may still need to fool around with tabs to get the description into one field, but at least it'll be on one line, which I find very helpful.