Get index creation date from SQL server - sql

How can I find the create date of an index. I am using SQL2008 R2.
I checked sys.indexes but it does not have a create date so I joined the query with sys.objects. The thing is that the object id for an index and the table containing that index is same.
I am using this query...
select i.name, i.object_id, o.create_date, o.object_id, o.name
from sys.indexes i
join sys.objects o on i.object_id=o.object_id
where i.name = 'Index_Name'
Thanks!

For indexes that are constraints, then see marc_s' answer
For other indexes, you'd have to use STATS_DATE to get the creation time of the associated index (every index has statistics on it)
Something like (not tested)
SELECT STATS_DATE(OBJECT_ID('MyTable'),
(SELECT index_id FROM sys.indexes WHERE name = 'Index_Name'))
This relies on the sys.indexes to sys.stats links
Edit: there is no way to find out as far as anyone can find out. Sorry.

Simple query to list indexes in descending date (of statistics) order.
This date is the sate of last statistics update, so is only reliable for recently created indexes.
select STATS_DATE(so.object_id, index_id) StatsDate
, si.name IndexName
, schema_name(so.schema_id) + N'.' + so.Name TableName
, so.object_id, si.index_id
from sys.indexes si
inner join sys.tables so on so.object_id = si.object_id
order by 1 desc

This is now quite a long dead thread but the below query from SQLPanda got me the info I needed on Azure SQL for a non clustered index:
SELECT OBJECT_NAME(i.object_id) AS TableName, i.object_id, i.name, i.type_desc,o.create_date, o.modify_date,o.type,i.is_disabled
FROM sys.indexes i
INNER JOIN sys.objects o ON i.object_id = o.object_id
WHERE o.type NOT IN ('S', 'IT')
AND o.is_ms_shipped = 0
AND i.name IS NOT NULL
ORDER BY modify_date DESC
Credit to http://www.sqlpanda.com/2013/10/how-to-check-index-creation-date.html
I just added the modified date since that was the info I was interested in.

Try this:
SELECT
i.name 'Index Name',
o.create_date
FROM
sys.indexes i
INNER JOIN
sys.objects o ON i.name = o.name
WHERE
o.is_ms_shipped = 0
AND o.type IN ('PK', 'FK', 'UQ')
The object_id refers to the table the index is created on....

When PK or UK is created, SQL Server automatically creates unique index for that constraints. The create_date of those constraints will be the same as the create date for the corresponding indexes.
Since the sys.indexes view does not have create_date column it is absolutely useless for searching this kind of information. Furthermore, object_id column in this view will never refer to the corresponding constraint. It will point to the table the index belongs to.
The following test will demonstrate the point:
CREATE TABLE dbo.TEST_T1
(
COLUMN_1 INT NOT NULL,
COLUMN_2 INT NOT NULL,
CONSTRAINT PK_TEST_T1 PRIMARY KEY (COLUMN_1)
)
GO
WAITFOR DELAY '00:00:01';
ALTER TABLE dbo.TEST_T1
ADD CONSTRAINT UK_TEST_T1 UNIQUE (COLUMN_2)
GO
SELECT O.name, O.object_id, O.create_date, I.object_id, I.name AS index_name
FROM sys.objects AS O
LEFT OUTER JOIN sys.indexes AS I ON O.object_id = i.object_id
WHERE O.name IN ('TEST_T1', 'PK_TEST_T1', 'UK_TEST_T1')
The result is:
name object_id create_date object_id index_name
PK_TEST_T1 272720024 2015-03-17 11:02:47.197 NULL NULL
TEST_T1 256719967 2015-03-17 11:02:47.190 256719967 PK_TEST_T1
TEST_T1 256719967 2015-03-17 11:02:47.190 256719967 UK_TEST_T1
UK_TEST_T1 288720081 2015-03-17 11:02:48.207 NULL NULL
So, if you want to see create_date for PK or UK indexes there is no need to join with sys.indexes. You should select from sys.objects:
SELECT name, object_id, create_date
FROM sys.objects
WHERE name IN ('PK_TEST_T1', 'UK_TEST_T1')
AND type IN ('PK', 'UQ')
The result is:
name object_id create_date
PK_TEST_T1 272720024 2015-03-17 11:02:47.197
UK_TEST_T1 288720081 2015-03-17 11:02:48.207

USE [YourDB Name]
SET NOCOUNT ON
DECLARE #Table_Name varchar(200)
DECLARE #Index_Name varchar(200)
DECLARE #Index_Type varchar(50)
DECLARE Indx_Cursor CURSOR
STATIC FOR
select s_tab.name as Table_Name,
s_indx.name as Index_Name,
s_indx.type_desc as Index_Type
from sys.indexes s_indx
inner join sys.tables s_tab
on s_tab.object_id=s_indx.object_id
where s_indx.name is not null;
OPEN Indx_Cursor
IF ##CURSOR_ROWS > 0
BEGIN
FETCH NEXT FROM Indx_Cursor INTO #Table_Name,#Index_Name,#Index_Type
WHILE ##Fetch_status = 0
BEGIN
INSERT INTO INDEX_HISTORY(table_name,index_name,Index_Type,Created_date)
SELECT #Table_Name,#Index_Name,#Index_Type,
STATS_DATE(OBJECT_ID(#Table_Name),
(SELECT index_id FROM sys.indexes
WHERE name = #Index_Name))as Index_create_Date
FETCH NEXT
FROM Indx_Cursor
INTO #Table_Name,#Index_Name,#Index_Type
END
END
CLOSE Indx_Cursor
DEALLOCATE Indx_Cursor
select distinct * from index_history
But the main problem with indexes is that when we rebuild or reorganize indexes then the index creation date gets changed to the date when the index was last rebuilt or reorganized.

select
crdate, i.name, object_name(o.id)
from
sysindexes i
join
sysobjects o ON o.id = i.id
where
i.name = 'My_Index_Name'

Related

Check to see if table exists and if table is null

I'm building a package in SSIS that first acquires source data from from another server and loads into my server. From there I have another package that manipulates this source data and loads a new table.
I want to prevent this 'manipulation' package from running if something failed on my 'source' package. I can talk it out but not Syntax it out...
If MyTABLE exists and count(*) from MyTABLE > 0 then 'GOOD' else 'BAD' I was going to have a constraint that wouldn't run the rest of the package if anything came back bad. If this is an asinine way of achieving this then please show me the easier way to achieve this.
The ultimate goal would be to have a list of 'GOOD' or 'BAD' and the table name as the next column so if anything fails I can get an email of my query that would quickly show me what is bad and what is good.
Source_Check Source_Table
GOOD TABLE1
BAD TABLE2
GOOD TABLE3
etc.....
my issue is I get an error trying to count(*) from a table that doesn't exist... Not sure how to overcome this :(
There are probably easier ways to go about this, I'm just a newb is all. Could phrase my search right to get any results from google.
Metadata is going to be your friend. Assuming SQL Server, you can write a simple query like
SELECT
*
FROM
sys.schemas AS S
INNER JOIN sys.tables AS T
ON T.schema_id = S.schema_id
WHERE
S.name = N'dbo'
AND T.name = N'SomeTable';
If that returns a result, then you know your table exists.
The problem with SELECT COUNT(*) is that the table must exist. It also locks forces you to crawl the table. There are tricks for addressing this but my favorite is to go back to the metadata well. Look at this query. It's going to generate a list of all the tables and their row counts in no time at all.
SELECT
s.[Name] as [Schema]
, t.[name] as [Table]
, SUM(p.rows) as [RowCount]
FROM
sys.schemas s
LEFT OUTER JOIN
sys.tables t
ON s.schema_id = t.schema_id
LEFT OUTER JOIN
sys.partitions p
ON t.object_id = p.object_id
LEFT OUTER JOIN
sys.allocation_units a
ON p.partition_id = a.container_id
WHERE
p.index_id in(0,1) -- 0 heap table , 1 table with clustered index
AND p.rows is not null
AND a.type = 1 -- row-data only , not LOB
GROUP BY
s.[Name]
, t.[name]
ORDER BY
1
, 2
Now you can compare that resultset to your list of tables that may or may not exist.
You could try something like this:
DECLARE #SourceTables TABLE (tbl_name VARCHAR(100))
INSERT INTO #SourceTables VALUES('TABLE1'),('TABLE2'),('TABLE3');
WITH CTE
AS
(
SELECT o.name AS tbl_name,
i.[Rows] AS row_count
FROM sysindexes i
INNER JOIN sysobjects o
ON i.id = o.id
WHERE i.IndId < 2
AND xtype = 'U'
)
--Returns tables that don't exist
SELECT CASE
WHEN B.tbl_name IS NULL AND B.row_count > 0 --when there is no table and row count is greater than 0, then good
THEN 'Good'
ELSE 'Bad'
END AS Source_Check,
A.tbl_name
FROM #SourceTables A
LEFT JOIN CTE B
ON A.tbl_name = B.tbl_name
Theoretical Results:
Source_Check tbl_name
------------ -------------------------
Good TABLE1
Good TABLE2
Bad TABLE3
I assume you're using SQL Server based on the SSIS package. You could simplify things using OBJECT_ID Try Something Like the following....
CREATE TABLE #OUTPUT(Source_Check VARCHAR(10), Source_Table VARCHAR(10))
IF OBJECT_ID('DBNAME.dbo.Table1') IS NOT NULL
BEGIN
INSERT INTO #OUTPUT VALUES ('GOOD', 'TABLE1')
END
ELSE
INSERT INTO #OUTPUT VALUES ('BAD', 'TABLE1')
END
IF OBJECT_ID('DBNAME.dbo.Table2') IS NOT NULL
BEGIN
INSERT INTO #OUTPUT VALUES ('GOOD', 'TABLE2')
END
ELSE
INSERT INTO #OUTPUT VALUES ('BAD', 'TABLE2')
END
IF OBJECT_ID('DBNAME.dbo.Table3') IS NOT NULL
BEGIN
INSERT INTO #OUTPUT VALUES ('GOOD', 'TABLE3')
END
ELSE
INSERT INTO #OUTPUT VALUES ('BAD', 'TABLE3')
END
SELECT * FROM #OUTPUT

SQLServer - How to find dependent tables on my table?

Using SQLServer :
I have a table user :
id
name
email
There are some other tables (about 200 more tables), some of which use user.id as foreign key on cascade delete.
So, I want to find out - Which tables use this foreign key (user.id) ?
I am accessing my sql-server with SQL Server Management Studio.
The way to get ONLY TABLE references (i.e. tables that uses given table as a foreign key and tables that given table uses the same way) you can use this code snippet:
declare #tableName varchar(64);
set #tableName = 'TABLE';
select
SO_P.name as [parent table]
,SC_P.name as [parent column]
,'is a foreign key of' as [direction]
,SO_R.name as [referenced table]
,SC_R.name as [referenced column]
,*
from sys.foreign_key_columns FKC
inner join sys.objects SO_P on SO_P.object_id = FKC.parent_object_id
inner join sys.columns SC_P on (SC_P.object_id = FKC.parent_object_id) AND (SC_P.column_id = FKC.parent_column_id)
inner join sys.objects SO_R on SO_R.object_id = FKC.referenced_object_id
inner join sys.columns SC_R on (SC_R.object_id = FKC.referenced_object_id) AND (SC_R.column_id = FKC.referenced_column_id)
where
((SO_P.name = #tableName) AND (SO_P.type = 'U'))
OR
((SO_R.name = #tableName) AND (SO_R.type = 'U'))
In SQL server management studio, you can right click your table in the object explorer, and then select 'View Dependencies'. This will open a new window in which you can see all other objects (not just tables) that depend on your table, and on which your table depends.
Here is a stored procedure I put together based in part on the above answer.
-- =============================================
-- Author: R. Mycroft
-- Create date: 2012-08-08
-- Description: Lists foreign keys to & from a named table.
-- (Have yet to find this one via Google!)
-- =============================================
alter procedure usp_ListTableForeignKeys
#tableName varchar(300) = ''
as
begin
set nocount on;
select
object_name(parent_object_id) as childObjectName
, object_name(referenced_object_id) as parentObjectName
, name, type_desc, create_date
from sys.foreign_keys
where object_name(parent_object_id) = #tableName
or object_name(referenced_object_id) = #tableName
end
Using SSMS GUI:
In SQL server management studio (SSMS), you can right click your table and select 'View Dependencies'. This will open a new window in which you can see all the objects that depend on your table, and on which your table depends also.
Additionally If you want to do it with TSQL in where all objects that depends on your table
Approach-1: Using sp_depends store procedure , though sql server team is going to remove this feauture in future version but it still useful to get all the dependencies on the specified Object, includes Tables, Views, Stored Procedures, Constraints, etc., sql server team recommend to use sys.dm_sql_referencing_entities and sys.dm_sql_referenced_entities instead.
-- Query to find Table Dependencies in SQL Server:
EXEC sp_depends #objname = N'dbo.aspnet_users' ;
Approach-2:
-- Query to find Table Dependencies in SQL Server:
SELECT referencing_id,
referencing_schema_name,
referencing_entity_name
FROM sys.dm_sql_referencing_entities('dbo.aspnet_users', 'OBJECT');
Approach-3: Find Table dependencies in Function, Procedure and View
SELECT *
FROM sys.sql_expression_dependencies A, sys.objects B
WHERE referenced_id = OBJECT_ID(N'dbo.aspnet_users') AND
A.referencing_id = B.object_id
Approach-4:
-- Value 131527 shows objects that are dependent on the specified object
EXEC sp_MSdependencies N'dbo.aspnet_users', null, 1315327
If you want to get all objects on which your table depends on.
-- Value 1053183 shows objects that the specified object is dependent on
EXEC sp_MSdependencies N'dbo.aspnet_users', null, 1053183
If you've got these defined as foreign keys then just examine the table design and look at the Relationships dialog which will show you everything that's defined for the table.
Alternatively you can use "View Dependencies".
Try this
select
OBJECT_NAME(parent_object_id) as parent_object_name,
*
from sys.foreign_keys
where name = 'YourFKName'
Another option to get foreign keys.
-- CTE to fetch all primary key information.
WITH PrimaryKeys AS (
SELECT
s.name as [Schema],
t.name as [Table],
c.name as [Column],
ic.index_column_id AS [ColumnNumber]
FROM sys.index_columns ic
JOIN sys.columns c ON ic.object_id = c.object_id and ic.column_id = c.column_id
JOIN sys.indexes i ON ic.object_id = i.object_id and ic.index_id = i.index_id
JOIN sys.tables t ON i.object_id = t.object_id
JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE i.is_primary_key = 1
),
-- CTE to fetch table information.
TableInfo AS (
SELECT
tab.name AS [Table],
col.name AS [Column],
sch.name AS [Schema],
tab.object_id AS TableId,
col.column_id AS ColumnId
FROM sys.tables tab
JOIN sys.schemas sch ON tab.schema_id = sch.schema_id
JOIN sys.columns col ON col.object_id = tab.object_id
)
-- Primary query selecting foreign keys and primary/dependent information.
SELECT
obj.name AS FK_NAME,
p.[Schema] AS [PrimarySchema],
p.[Table] AS [PrimaryTable],
p.[Column] AS [PrimaryColumn],
d.[Schema] AS [DependentSchema],
d.[Table] AS [DependentTable],
d.[Column] AS [DependentColumn],
prim.ColumnNumber AS IsDependentPrimaryColumn -- has value if is part of dependent table's primary key
FROM sys.foreign_key_columns fkc
JOIN sys.objects obj ON obj.object_id = fkc.constraint_object_id
JOIN TableInfo d ON d.TableId = fkc.parent_object_id AND d.ColumnId = fkc.parent_column_id
JOIN TableInfo p ON p.TableId = fkc.referenced_object_id AND p.ColumnId = fkc.referenced_column_id
-- Join in primary key information to determine if the dependent key is also
-- part of the dependent table's primary key.
LEFT JOIN PrimaryKeys prim ON prim.[Column] = d.[Column] AND prim.[Table] = d.[Table]
ORDER BY [PrimarySchema], [PrimaryTable], [DependentSchema], [DependentTable]
This will yield all foreign keys and their primary/dependent information. It also includes an extra column if the dependent column is part of the primary key in the dependent table - sometimes important to note that.
To get only the Users table, just add a WHERE clause before the final ORDER BY
WHERE PrimaryTable = 'Users'
Option to get all tables with Schema Names
select
SO_P.name as [parent table]
,SS_P.name as [parent table schema]
,SC_P.name as [parent column]
,'is a foreign key of' as [direction]
,SO_R.name as [referenced table]
,SS_R.name as [referenced table schema]
,SC_R.name as [referenced column]
,*
from sys.foreign_key_columns FKC
inner join sys.objects SO_P on SO_P.object_id = FKC.parent_object_id
inner join sys.schemas SS_P on SS_P.schema_id = SO_P.schema_id
inner join sys.columns SC_P on (SC_P.object_id = FKC.parent_object_id) AND (SC_P.column_id = FKC.parent_column_id)
inner join sys.objects SO_R on SO_R.object_id = FKC.referenced_object_id
inner join sys.schemas SS_R on SS_R.schema_id = SO_P.schema_id
inner join sys.columns SC_R on (SC_R.object_id = FKC.referenced_object_id) AND (SC_R.column_id = FKC.referenced_column_id)
where SO_P.type = 'U' OR SO_R.type = 'U'

SQL Server 2008: I have 1000 tables, I need to know which tables have data

Is there a way in SMSS to detect whether a table has any records? I need to get a list of tables that have records. perhaps there is a sql statement that will do the trick?
Try this - gives you the table name and the row count:
SELECT
t.NAME AS TableName,
SUM(p.rows) AS [RowCount]
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE
i.index_id <= 1
GROUP BY
t.NAME, i.object_id, i.index_id, i.name
ORDER BY
SUM(p.rows) DESC
It shows all tables and their row counts in a single output.
A simpler syntax:
SELECT
[Name] = o.name,
[RowCount]= SUM(p.row_count)
FROM SYS.DM_DB_PARTITION_STATS p
INNER JOIN SYS.TABLES o ON p.[object_ID] = o.[object_id]
WHERE index_id <= 1 -- Heap or clustered index only
GROUP BY o.name
ORDER BY 2 desc
As your question specifically mentions SSMS you can also right click the database in object explorer and then from the short cut menu do
Reports -> Standard Reports -> Disc Usage By Table
You can use this stored procedure:
EXEC sp_MSforeachtable #command1="EXEC sp_spaceused '?'"
This will return a resultset for each table in the database (each showing the name, and the number of rows, among other information).
Here is how you can put them into a table variable, and order them by the number of rows:
DECLARE #TBL TABLE (
[name] nvarchar(500),
[rows] bigint,
[reserved] nvarchar(500),
[data] nvarchar(500),
[index_size] nvarchar(500),
[unused] nvarchar(500)
)
INSERT INTO #TBL
EXEC sp_MSforeachtable #command1="EXEC sp_spaceused '?'"
SELECT * FROM #TBL
ORDER BY [rows] DESC
Hope, It helps you-
SELECT name AS [TableList] FROM SYS.DM_DB_PARTITION_STATS s
INNER JOIN sys.tables t ON t.[object_id] = s.[object_id]
WHERE row_count = 0
This code shows that list of tables, which does not contain any data or row.
Thanks!!!

Please tell me how to get primary key name in SQL Server 2005

I need a primary key name and primary key column name of a table please tell me what query should I write..
declare #tableName as nvarchar(100)
set #tableName = 'table'
select i.name, c.name
from sys.index_columns ic
join sys.indexes i on ic.index_id=i.index_id
join sys.columns c on c.column_id=ic.column_id
where
i.[object_id] = object_id(#tableName) and
ic.[object_id] = object_id(#tableName) and
c.[object_id] = object_id(#tableName) and
is_primary_key = 1
Here's another option that uses the INFORMATION_SCHEMA views
SELECT
cu.Table_Catalog,
cu.Table_Schema,
cu.table_name,
cu.Constraint_name ,
cu.column_name
FROM
sys.indexes si
inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu
on si.name = cu.constraint_name
WHERE
is_primary_key = 1
Not quite what you're looking for, but you can play around with it:
SQL 2000: T-SQL to get foreign key relationships for a table
Just a performance note - the select using sys tables is a couple orders of magnitude faster than the select that uses INFORMATION_SCHEMA views

Determine a table's primary key using TSQL

I'd like to determine the primary key of a table using TSQL (stored procedure or system table is fine). Is there such a mechanism in SQL Server (2005 or 2008)?
This should get you started:
SELECT
*
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON tc.CONSTRAINT_NAME = ccu.Constraint_name
WHERE
tc.TABLE_NAME = 'TableName' AND
tc.CONSTRAINT_TYPE = 'Primary Key'
How about
sp_pkeys 'TableName'
Here's one based on system tables from SQL 2005 (99% sure it'd work in 2008). This will list all PKs for all user-defined tables, with all columns and some extra fluff that could be removed. Add parameters to pick out a table at a time.
SELECT
schema_name(ta.schema_id) SchemaName
,ta.name TableName
,ind.name
,indcol.key_ordinal Ord
,col.name ColumnName
,ind.type_desc
,ind.fill_factor
from sys.tables ta
inner join sys.indexes ind
on ind.object_id = ta.object_id
inner join sys.index_columns indcol
on indcol.object_id = ta.object_id
and indcol.index_id = ind.index_id
inner join sys.columns col
on col.object_id = ta.object_id
and col.column_id = indcol.column_id
where ind.is_primary_key = 1
order by
ta.name
,indcol.key_ordinal
SELECT ccu.COLUMN_NAME, ccu.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu
ON tc.CONSTRAINT_NAME = ccu.CONSTRAINT_NAME
WHERE tc.TABLE_CATALOG = 'Your_Catalog' -- replace with your catalog
AND tc.TABLE_SCHEMA = 'dbo' -- replace with your schema
AND tc.TABLE_NAME = 'Your_Table' -- replace with your table name
AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
exec [sys].[sp_primary_keys_rowset] #table_name= 'TableName'
EXEC sp_Pkeys #tableName
You're better off using INFORMATION_SCHEMA.KEY_COLUMN_USAGE, as you can access the key ordering information (ORDINAL_POSITION) which is very important to know.
SELECT
kcu.*
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
ON tc.TABLE_NAME = kcu.TABLE_NAME AND
tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
ORDER BY
tc.TABLE_NAME,
tc.CONSTRAINT_NAME,
kcu.ORDINAL_POSITION
The simplest way is this!
select object_id from sys.objects
where parent_object_id = OBJECT_ID(N'FACounty')
and [type] = N'PK'
Can't add a comment, not enough rep points, but this is in response to those saying sp_Pkeys is not usable. Doesn't have to be a function as mentioned in another comment to an answer.
DECLARE #tbl TABLE
(
Table_Qualifier varchar(30),
Table_Owner varchar(30),
Table_Name varchar(50),
Column_Name varchar(30),
Key_Seq int,
PK_Name varchar(50)
)
insert into #tbl EXEC sp_Pkeys 'tablename'
select * from #tbl
If you already know the name of the key you're interested in, following works:
-- Assuming you have schema "Example" and the primary key name is "PK_Item"
-- Notice that name of table is irrelevant here but is "Foobar" here
IF (OBJECT_ID('Example.PK_ITEM') IS NULL)
BEGIN
ALTER TABLE [Example].Foobar ADD CONSTRAINT
PK_Item PRIMARY KEY ...
END