How to get the statistics existing on a column, if any? - sql-server-2005

I want to check in Transact SQL if a specific column in a table has statistics and if so to get them all.

This query should do it.
I use it in a stored proc that browse the DB to find stats.
Works in SQL Server 2005 and probably older version as well.
SELECT S.NAME
FROM SYS.OBJECTS AS O
INNER JOIN SYS.STATS AS S
ON O.OBJECT_ID = S.OBJECT_ID
INNER JOIN SYS.STATS_COLUMNS AS SC
ON SC.OBJECT_ID = S.OBJECT_ID
AND S.STATS_ID = SC.STATS_ID
WHERE (O.OBJECT_ID = OBJECT_ID('MyTable','local'))
AND (O.TYPE IN ('U'))
AND (INDEXPROPERTY(S.OBJECT_ID,S.NAME,'IsStatistics') = 1) /* only stats */
AND (COL_NAME(SC.OBJECT_ID,SC.COLUMN_ID) = 'MyColumn')

Related

How to get table row count in SQL Server?

There's a requirement where I need to get the table row count information without using count function. Currently I have used the below code to achieve it:
SELECT
CONCAT(schemas.name, '.', tables.name) as tableName,
partitions.rows AS tableRowCount
FROM
sys.partitions
JOIN
sys.tables ON tables.object_id = partitions.object_id
JOIN
sys.schemas ON tables.schema_id = schemas.schema_id
But for some reason, this query is not working properly as expected. Having said that, in some cases tableRowCount is different if the same is checked using the count function.
Is there a way to overcome this challenge?
Please note I tried using sys.dm_db_partition_stats table as well.
However, I get this error:
Msg 104385, Level 16, State 1, Line 9
Catalog view 'dm_db_partition_stats' is not supported in this version.
Please help.
This should be much faster than using COUNT.
SELECT SUM(p.rows) FROM sys.partitions AS p
INNER JOIN sys.tables AS t ON p.[object_id] = t.[object_id]
INNER JOIN sys.schemas AS s ON s.[schema_id] = t.[schema_id]
WHERE t.name = N'(yourtable)' AND s.name = N'dbo' AND p.index_id IN (0,1);
Note that this approach is in no way portable between RDBMSs.

Selecting a Custom Column Type across all tables in a SQL Server 2005/2008

Currently, I have a query that uses the sys tables to return all the tables and column names where the column is a specific custom type, the query looks like this:
select
schemas.name, obj.name, col.name
from
sys.objects obj
inner join
sys.columns col on col.object_id = obj.object_id
inner join
sys.types types on types.user_type_id = col.user_type_id
inner join
sys.schemas schemas on obj.schema_id = schemas.schema_id
where
types.name = 'myCustomType'
However, the security of the SQL Server database is being changed and we can no longer query the sys tables. How else can I query for this information?

How to determine if a specific set of tables in a database are empty

I have database A which contains a table (CoreTables) that stores a list of active tables within database B that the organization's users are sending data to.
I would like to be able to have a set-based query that can output a list of only those tables within CoreTables that are populated with data.
Dynamically, I normally would do something like:
For each row in CoreTables
Get the table name
If table is empty
Do nothing
Else
Print table name
Is there a way to do this without a cursor or other dynamic methods? Thanks for any assistance...
Probably the most efficient option is:
SELECT c.name
FROM dbo.CoreTables AS c
WHERE EXISTS
(
SELECT 1
FROM sys.partitions
WHERE index_id IN (0,1)
AND rows > 0
AND [object_id] = OBJECT_ID(c.name)
);
Just note that the count in sys.sysindexes, sys.partitions and sys.dm_db_partition_stats are not guaranteed to be completely in sync due to in-flight transactions.
While you could just run this query in the context of the database, you could do this for a different database as follows (again assuming that CoreTables does not include schema in the name):
SELECT c.name
FROM DatabaseA.CoreTables AS c
WHERE EXISTS
(
SELECT 1
FROM DatabaseB.sys.partitions AS p
INNER JOIN DatabaseB.sys.tables AS t
ON p.[object_id] = t.object_id
WHERE t.name = c.name
AND p.rows > 0
);
If you need to do this for multiple databases that all contain the same schema (or at least overlapping schema that you're capturing in aggregate in a central CoreTables table), you might want to construct a view, such as:
CREATE VIEW dbo.CoreTableCounts
AS
SELECT db = 'DatabaseB', t.name, MAX(p.rows)
FROM DatabaseB.sys.partitions AS p
INNER JOIN DatabaseB.sys.tables AS t
ON p.[object_id] = t.[object_id]
INNER JOIN DatabaseA.dbo.CoreTables AS ct
ON t.name = ct.name
WHERE p.index_id IN (0,1)
GROUP BY t.name
UNION ALL
SELECT db = 'DatabaseC', t.name, rows = MAX(p.rows)
FROM DatabaseC.sys.partitions AS p
INNER JOIN DatabaseC.sys.tables AS t
ON p.[object_id] = t.[object_id]
INNER JOIN DatabaseA.dbo.CoreTables AS ct
ON t.name = ct.name
WHERE p.index_id IN (0,1)
GROUP BY t.name
-- ...
GO
Now your query isn't going to be quite as efficient, but doesn't need to hard-code database names as object prefixes, instead it can be:
SELECT name
FROM dbo.CoreTableCounts
WHERE db = 'DatabaseB'
AND rows > 0;
If that is painful to execute you could create a view for each database instead.
In SQL Server, you can do something like:
SELECT o.name, st.row_count
FROM sys.dm_db_partition_stats st join
sys.objects o
on st.object_id = o.object_id
WHERE index_id < 2 and st.row_count > 0
By the way, this specifically does not use OBJECT_ID() or OBJECT_NAME() because these are evaluated in the current database. The above code continues to work for another database, using 3-part naming. This version also takes into account multiple partitions:
SELECT o.name, sum(st.row_count)
FROM <dbname>.sys.dm_db_partition_stats st join
<dbname>.sys.objects o
on st.object_id = o.object_id
WHERE index_id < 2
group by o.name
having sum(st.row_count) > 0
something like this?
//
foreach (System.Data.DataTable dt in yourDataSet.Tables)
{
if (dt.Rows.Count != 0) { PrintYourTableName(dt.TableName); }
}
//
This is a way you can do it, that relies on system tables, so be AWARE it may not always work in future versions of SQL. With that strong caveat in mind.
select distinct OBJECT_NAME(id) as tabName,rowcnt
from sys.sysindexes si
join sys.objects so on si.id=si.id
where indid=1 and so.type='U'
You would add to the where clause the tables you are interested in and rowcnt <1

How to discover trigger's parent schema?

To discover all triggers in any given MS SQL Server database, I'm currently querying the sysobjects table (which is fine because it works in MS SQL Server 2000 which I have to support) e.g.
SELECT R1.name AS trigger_name,
T1.name AS trigger_parent_table_name
FROM sysobjects AS R1
INNER join sysobjects AS T1
ON R1.parent_obj = T1.id
WHERE R1.xtype = 'tr';
This gives me a reduced list of trigger names and for each I can use
EXEC sp_helptext 'trigger_name_here'
to find the definition. That works fine for databases where only the default dbo schema is used.
I now have a MS SQL Server 2005 database which uses multiple schemas. What is the best way of discovering the schema for each trigger?
You are looking for the parent object for a trigger so it will always be a table. In sys.tables (system view) you get the schema_id and with it you can go sys.schemas (system view too) to get the schema's name.
Hope this helps.
--
EDIT:
The code:
SELECT sys.objects.name AS [trigger],
sys.tables.name AS [table],
sys.objects.type,
sys.schemas.name AS [schema]
FROM sys.schemas RIGHT OUTER JOIN
sys.tables ON sys.schemas.schema_id = sys.tables.schema_id RIGHT OUTER JOIN
sys.objects ON sys.tables.object_id = sys.objects.parent_object_id
WHERE sys.objects.type = 'tr'
This is is with sys.tables but you can do it with only sys.objects, this is a general select to look for parents and schemas:
SELECT O.name, O.type, S.name AS [schema],
OP.name AS parent_name, OP.type AS parent_type, SP.name AS parent_schema
FROM sys.schemas AS SP RIGHT OUTER JOIN
sys.objects AS OP ON SP.schema_id = OP.schema_id RIGHT OUTER JOIN
sys.objects AS O LEFT OUTER JOIN
sys.schemas AS S ON O.schema_id = S.schema_id ON OP.object_id = O.parent_object_id

List of Stored Procedure from Table

I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table.
sys.sql_dependencies has a list of entities with dependencies, including tables and columns that a sproc includes in queries. See this post for an example of a query that gets out dependencies. The code snippet below will get a list of table/column dependencies by stored procedure
select sp.name as sproc_name
,t.name as table_name
,c.name as column_name
from sys.sql_dependencies d
join sys.objects t
on t.object_id = d.referenced_major_id
join sys.objects sp
on sp.object_id = d.object_id
join sys.columns c
on c.object_id = t.object_id
and c.column_id = d.referenced_minor_id
where sp.type = 'P'
select
so.name,
sc.text
from
sysobjects so inner join syscomments sc on so.id = sc.id
where
sc.text like '%INSERT INTO xyz%'
or sc.text like '%UPDATE xyz%'
This will give you a list of all stored procedure contents with INSERT or UPDATE in them for a particular table (you can obviously tweak the query to suit). Also longer procedures will be broken across multiple rows in the returned recordset so you may need to do a bit of manual sifting through the results.
Edit: Tweaked query to return SP name as well. Also, note the above query will return any UDFs as well as SPs.
Use sys.dm_sql_referencing_entities
Note that sp_depends is obsoleted.
MSDN Reference
You could try exporting all of your stored procedures into a text file and then use a simple search.
A more advanced technique would be to use a regexp search to find all SELECT FROM and INSERT FROM entries.
If you download sp_search_code from Vyaskn's website it will allow you to find any text within your database objects.
http://vyaskn.tripod.com/sql_server_search_stored_procedure_code.htm
This seems to work:
select
so.name as [proc],
so2.name as [table],
sd.is_updated
from sysobjects so
inner join sys.sql_dependencies sd on so.id = sd.object_id
inner join sysobjects so2 on sd.referenced_major_id = so2.id
where so.xtype = 'p' -- procedure
and is_updated = 1 -- proc updates table, or at least, I think that's what this means
SELECT Distinct SO.Name
FROM sysobjects SO (NOLOCK)
INNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID
AND SO.Type = 'P'
AND (SC.Text LIKE '%UPDATE%' OR SC.Text LIKE '%INSERT%')
ORDER BY SO.Name
This link was used as a resource for the SP search.