I shared few SQL queries useful in analyzing database, which I use quite often. This query will return all table names and no.of rows in it for built-in tables.
-
- SELECT distinct t.name,prt.rows
- FROM sys.tables t INNER JOIN sys.partitions AS prt
- ON t.object_id = prt.object_id where t.is_ms_shipped=1
- order by prt.rows desc
This query will return column names and its data type of a table.
-
- SELECT cols.name,t.name
- FROM sys.objects o join sys.columns cols on o.object_id= cols.object_id
- join sys.types t on t.system_type_id=cols.system_type_id
- and o.name='Employee'
This query will return file name, its size and file group name of a database.
- SELECT sdf.name AS [FileName],
- size/128 AS [Size],
- fg.name AS [File_Group_Name]
- FROM sys.database_files sdf
- INNER JOIN
- sys.filegroups fg
- ON sdf.data_space_id=fg.data_space_id
Batch file to execute all sql files in a directory, Save it as .bat in a folder that have sql script files to be executed.
- @Echo Off
- FOR /f %%i IN ('DIR *.Sql /B') do call :RunSql %%i
- GOTO :END
- :RunSql
- Echo Executing SQL: %1
- SQLCMD -S server1 -U user1 -P pwd1 -d DB1 -i %1
- Echo Completed SQL: %1
- :END
This query will return all table names that have a Foreign key:
- SELECT SCHEMA_NAME(schema_id) AS SchemaName,
- name AS TableName
- FROM sys.tables where OBJECTPROPERTY(OBJECT_ID,'TableHasForeignKey') = 1