Why the table sys.sql_modules is empty? - sql

In SSMS, I create a database using the following script. When the script execution completes, I would expect to see the CREATE TABLE statement in the sql_modules table. However I can't find it.
CREATE DATABASE [MyDb]
GO
USE [MyDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MyTable] (
[UID] [uniqueidentifier] NOT NULL,
[DateTime] [datetime] NOT NULL
)
Here's the query I run the get the table definition. However, I get three empty result sets. Any idea why I am getting those three empty results set?
USE MyDb
GO
SELECT *
FROM sys.sql_modules
SELECT *
FROM sys.triggers
SELECT sm.object_id, OBJECT_NAME(sm.object_id) AS object_name, o.type, o.type_desc, sm.definition
FROM sys.sql_modules AS sm
JOIN sys.objects AS o ON sm.object_id = o.object_id
ORDER BY o.type;

To get columns and table information, this is a good place to start:
SELECT c.*, t.*
FROM sys.tables AS t
INNER JOIN sys.columns AS c ON t.object_id = c.object_id
INNER JOIN sys.schemas AS sch ON t.schema_id = sch.schema_id
WHERE sch.name = 'dbo'
AND t.name = 'YourTable'

Related

User can access stored procedure, but not the underlying code directly

I want to create a stored procedure SP1 which will have script to fetch data from sys schema. But this stored procedure would be called by users who do not have permissions on the sys schema. How can I achieve this?
I am doing this basically to mask the entire sys schema from that user but at the same time allowing him to see minimal info.
Basically I want this inside SP
--Displays Object information
SELECT m.object_id [ObjID]
,o.type_desc [ObjType]
,o.name [ObjectName]
,e.last_execution_time [LastExecutedOn]
,create_date [CreatedOn]
,modify_date [ModifiedOn]
, DEFINITION [Data]
FROM sys.SQL_MODULES m
JOIN sys.OBJECTS o
ON m.object_id=o.object_id
LEFT JOIN sys.dm_exec_procedure_stats e
ON e.object_id=o.object_id
WHERE DEFINITION LIKE '%'+#SearchStr+'%'
ORDER BY o.name
I believe you could achieve this with a View rather than an SP, as per this question.
If you need to be able to pass a parameter as well for your #SearchStr variable, you could create an SP which queries the view accordingly. So your View would be:
CREATE VIEW vwObjectInfo
AS
SELECT m.OBJECT_ID [ObjID],
o.type_desc [ObjType],
o.name [ObjectName],
e.last_execution_time [LastExecutedOn],
create_date [CreatedOn],
modify_date [ModifiedOn],
[definition] [Data]
FROM sys.SQL_MODULES m
JOIN sys.OBJECTS o ON m.OBJECT_ID = o.OBJECT_ID
LEFT JOIN sys.dm_exec_procedure_stats e ON e.OBJECT_ID = o.OBJECT_ID
and your SP would be:
CREATE PROCEDURE spSearchObjectInfo
#SearchStr NVARCHAR(MAX)
AS
BEGIN
SELECT * FROM vwObjectInfo
WHERE Data LIKE '%' + #SearchStr + '%'
ORDER BY ObjectName
END
Your user should then be able to call the SP with their desired search string and get results with just the ability to SELECT from the View and EXECUTE the SP, like so:
EXEC spSearchObjectInfo 'Some Search String'

Cannot join objects(tables) names using database_id

I cannot find a way to join objects using the database_id.
I am trying to write an audit query which scans through the tables by accepting the database name as parameter.
I want to avoid dynamic queries.
Is it possible?
like
SELECT *
FROM information_schema.tables a
JOIN sys.tables b
ON a.datbase_id = b.database_id
AND b.database_name = 'testdb'
Give this a go.
select *
from
INFORMATION_SCHEMA.TABLES it
inner join sys.tables st
on st.name = it.table_name
where it.TABLE_CATALOG = 'testdb'
First of all, there is no such column as database_id in information_schema.tables. Secondly there is an undocumented stored proc called sp_msForEachDb, which iterates through all the database one by one and runs the script that you want to, which you need to pass as a string input to it.
In your case, it seems that you want to join the information_schema.tables with sys.tables and list the tables for testDB database. Try the script below for that:
--Build a temp table to store the info
select * into #a
from INFORMATION_SCHEMA.TABLES it join sys.tables st
on st.name COLLATE SQL_Latin1_General_CP1_CI_AS= it.table_name COLLATE SQL_Latin1_General_CP1_CI_AS
where 1=0
insert into #a --This script runs for each database and populates the info into #a
EXECUTE master.sys.sp_MSforeachdb
'select * from INFORMATION_SCHEMA.TABLES it join [?].sys.tables st
on st.name COLLATE SQL_Latin1_General_CP1_CI_AS= it.table_name COLLATE SQL_Latin1_General_CP1_CI_AS
where it.TABLE_CATALOG = ''testdb'''
select * from #a

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'

Get index creation date from SQL server

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'

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!!!