Showing posts with label Utility. Show all posts
Showing posts with label Utility. Show all posts

Monday, March 28, 2022

How to find unsaved file location for SQL query in management studio

Losing unsaved work can be frustrating, especially in SQL Server Management Studio (SSMS). Here's how to recover your work.

Default Location for Unsaved SQL Files

SSMS may store unsaved queries in temporary locations:

  • Windows XP:
    C:\Documents and Settings\<YourUsername>\My Documents\SQL Server Management Studio\Backup Files
  • Windows Vista / 7 / 10 / 11:
    %USERPROFILE%\Documents\SQL Server Management Studio\Backup Files
    OR
    %USERPROFILE%\AppData\Local\Temp

Replace <YourUsername> with your actual Windows username.

View Recently Executed SQL Queries

Run this SQL to view recent activity:

USE <Database Name>;
SELECT 
    execquery.last_execution_time AS [Date Time],
    execsql.text AS [Script]
FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC;
⚠️ Replace <Database Name> with the name of your working database.

Enable AutoRecover in SSMS

  1. Open SSMS.
  2. Go to Tools > Options.
  3. Navigate to Environment > AutoRecover.

Adjust settings like time interval and number of backups to keep.

SSMS Auto recover Query

What Happens on Restart?

SSMS prompts to recover unsaved queries after a crash:

Choose-query-to-recover

Conclusion

Enable AutoRecover and know where unsaved files go to prevent data loss in SSMS.

Sunday, January 2, 2022

Read specific errors using temp table

 Read specific errors using a temp table

Ever need to quickly check recent errors in your SQL Server logs? This handy T-SQL snippet allows you to query the SQL Server error log and gather information about various processes and messages. It's a great way to get a snapshot of what's been happening in your SQL Server environment.

Querying SQL Server Error Logs

The following SQL code creates a temporary table and populates it by reading the last seven SQL Server error logs (from 0 to 6). It then selects all entries where the process is not 'logon', helping you filter out routine login messages and focus on actual errors or important events.

create table #t (dt datetime, process varchar(200), msg varchar(1000))
insert into #t exec sp_readerrorlog 0,1,'error'
insert into #t exec sp_readerrorlog 1,1,'error'
insert into #t exec sp_readerrorlog 2,1,'error'
insert into #t exec sp_readerrorlog 3,1,'error'
insert into #t exec sp_readerrorlog 4,1,'error'
insert into #t exec sp_readerrorlog 5,1,'error'
insert into #t exec sp_readerrorlog 6,1,'error'
select * from #t where process <> 'logon'
---

Further Reading and Related Topics

For more insights into SQL Server, error handling, and performance monitoring, check out these excellent resources:

Wednesday, December 29, 2021

Get a count of SQL connections by IP address

Here's a handy SQL query to get an overview of your active SQL Server connections and sessions. It helps you quickly see who is connected, from where, and how many connections they have open. This can be super useful for monitoring activity or troubleshooting connection issues.

SELECT ec.client_net_address
 ,es.[program_name]
 ,es.[host_name]
 ,es.login_name
 ,COUNT(ec.session_id) AS [connection count]
FROM sys.dm_exec_sessions AS es WITH (NOLOCK)
INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) ON es.session_id = ec.session_id
GROUP BY ec.client_net_address
 ,es.[program_name]
 ,es.[host_name]
 ,es.login_name
ORDER BY ec.client_net_address
 ,es.[program_name]
OPTION (RECOMPILE);

This query joins two dynamic management views (DMVs):

By grouping and counting, we can easily see the number of connections per unique combination of client IP address, program name, host name, and login name. The OPTION (RECOMPILE) ensures the query plan is recompiled each time it runs, which can be beneficial for DMVs that frequently change data.

Get tempdb version store space usage by database

Looking to understand how much space the version store is using in your SQL Server tempdb? The sys.dm_tran_version_store_space_usage dynamic management view is your go-to. It provides a table showing the total tempdb space consumed by version store records for each database.

This view is super efficient and inexpensive to run because it doesn't dig into individual version store records. Instead, it gives you an aggregated view of the version store space used in tempdb on a per-database basis. That makes it perfect for quick checks and monitoring!

Retrieve Version Store Space Usage

SELECT DB_NAME(database_id) AS [Database Name],
       reserved_page_count AS [Version Store Reserved Page Count],
       reserved_space_kb / 1024 AS [Version Store Reserved Space (MB)]
FROM sys.dm_tran_version_store_space_usage WITH (NOLOCK)
ORDER BY reserved_space_kb / 1024 DESC
OPTION (RECOMPILE);

This query will give you a clear breakdown of the version store space by database, ordered from largest to smallest.

For more SQL Server insights, check out this article on getting your TempDB files count.

You can also find more detailed documentation on sys.dm_tran_version_store_space_usage on the Microsoft Docs website.

Sunday, December 19, 2021

Hardware information from SQL Server

This query provides valuable basic hardware information about your database server.

It's important to note that a 'HYPERVISOR' value for 'virtual_machine_type_desc' doesn't automatically confirm SQL Server is running inside a virtual machine. This merely indicates that a hypervisor is present on your host machine.

SELECT cpu_count AS [Logical CPU Count], scheduler_count, 
       (socket_count * cores_per_socket) AS [Physical Core Count], 
       socket_count AS [Socket Count], cores_per_socket, numa_node_count,
       physical_memory_kb/1024 AS [Physical Memory (MB)], 
       max_workers_count AS [Max Workers Count], 
       affinity_type_desc AS [Affinity Type], 
       sqlserver_start_time AS [SQL Server Start Time],
       DATEDIFF(hour, sqlserver_start_time, GETDATE()) AS [SQL Server Up Time (hrs)],
       virtual_machine_type_desc AS [Virtual Machine Type], 
       softnuma_configuration_desc AS [Soft NUMA Configuration], --SQL Server 2016
       sql_memory_model_desc, --Added in SQL Server 2016 SP1
       container_type_desc -- New in SQL Server 2019
FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);

For more in-depth information, you can explore the following resources:

Monday, November 29, 2021

Manufacturer information inside SQL server

How to Identify Your System's Manufacturer and Model from the SQL Server Error Log

Did you know you can quickly pinpoint your SQL Server's system manufacturer and model number directly from its error log? It's a handy trick, especially when you need to gather system details without digging deep into system properties.

Using a Simple SQL Query

Here's the straightforward SQL query you can use:

EXEC sys.xp_readerrorlog 0, 1, N'Manufacturer';

This command searches the current SQL Server error log for entries containing the word "Manufacturer." The output will typically include a line detailing your system's make and model.

Important Considerations

Keep in mind that this query will only yield results if the error log hasn't been recycled since your SQL Server instance last started. If the log has cycled, the relevant information might no longer be present in the current log.

Verifying Virtual Machine Environments

Beyond just identifying the manufacturer, this method can also be used to confirm if your SQL Server is running within a virtual machine (VM). Many virtualized environments will clearly state "Virtual Machine" or similar in their manufacturer details.

Further Reading and Resources

For more advanced techniques on working with SQL Server error logs and system information, check out these related posts:

Saturday, November 13, 2021

How to check what databases are accessible?


Ever wonder which databases you can actually get into? There's a simple SQL query that'll show you exactly which ones are accessible on your system. It's a quick way to check your database permissions at a glance.


SELECT name, HAS_DBACCESS(name) FROM sys.databases;

This statement lists each database by name and tells you whether you have access to it. Pretty handy for a quick security check!



Friday, October 29, 2021

Read Windows Registry from SQL server

Ever wonder about the nitty-gritty details of your SQL Server's underlying hardware? Sometimes, peeking into the Windows Registry can give you some valuable insights. Here are a few handy SQL commands to pull essential hardware information, along with some important considerations for optimizing performance.

Unveiling Storage Driver Parameters

For those running SQL Server on VMware, understanding your storage driver settings is crucial for optimal I/O. You can query the registry to see the current driver parameters for your PVSCSI adapter:

EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device', N'DriverParameter';

VMware suggests specific values for intensive I/O workloads: RequestRingPages=32 and MaxQueueDepth=254. These settings can significantly impact your disk performance.

For more in-depth information, refer to the official VMware knowledge base article: https://kb.vmware.com/s/article/2053145

---

Discovering Your BIOS Release Date

Knowing your system's BIOS release date can be useful for troubleshooting or determining if you're running on an up-to-date firmware version. Here's how to retrieve it directly from the Windows Registry:

EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\BIOS', N'BiosReleaseDate';
---

Identifying Your Processor Details

Understanding your server's processor is fundamental to SQL Server performance tuning. You can grab the full processor description from the registry with this command:

EXEC sys.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';

For insights into processor selection for SQL Server and how it impacts performance, check out this valuable resource:

https://www.sqlskills.com/blogs/glenn/processor-selection-for-sql-server/

And if you're looking for a comprehensive utility to analyze your CPU and other system components, CPU-Z is a fantastic tool:

https://www.cpuid.com/softwares/cpu-z.html

Sunday, April 25, 2021

Find all comments in SQL server for all kind of objects

This post details how to retrieve records using extended properties within your SQL Server database. The following SQL scripts demonstrate how to query various database objects for their associated extended properties.

Objects and Columns

SELECT 
  CASE 
    WHEN ob.parent_object_id > 0
    THEN OBJECT_SCHEMA_NAME(ob.parent_object_id) + '.' + OBJECT_NAME(ob.parent_object_id) + '.' + ob.name
    ELSE OBJECT_SCHEMA_NAME(ob.object_id) + '.' + ob.name
  END + CASE 
    WHEN ep.minor_id > 0
    THEN '.' + col.name
    ELSE ''
  END AS path
  ,'schema' + CASE 
    WHEN ob.parent_object_id > 0
    THEN '/table'
    ELSE ''
  END + '/' + CASE 
    WHEN ob.type IN (
      'TF'
      ,'FN'
      ,'IF'
      ,'FS'
      ,'FT'
      )
    THEN 'function'
    WHEN ob.type IN (
      'P'
      ,'PC'
      ,'RF'
      ,'X'
      )
    THEN 'procedure'
    WHEN ob.type IN (
      'U'
      ,'IT'
      )
    THEN 'table'
    WHEN ob.type = 'SQ'
    THEN 'queue'
    ELSE LOWER(ob.type_desc)
  END + CASE 
    WHEN col.column_id IS NULL
    THEN ''
    ELSE '/column'
  END AS thing
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.objects ob ON ep.major_id = ob.OBJECT_ID
  AND class = 1
LEFT OUTER JOIN sys.columns col ON ep.major_id = col.Object_id
  AND class = 1
  AND ep.minor_id = col.column_id

Indexes

SELECT --indexes
  OBJECT_SCHEMA_NAME(ob.object_id) + '.' + OBJECT_NAME(ob.object_id) + '.' + ix.name
  ,'schema/' + LOWER(ob.type_desc) + '/index'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.objects ob ON ep.major_id = ob.OBJECT_ID
  AND class = 7
INNER JOIN sys.indexes ix ON ep.major_id = ix.Object_id
  AND class = 7
  AND ep.minor_id = ix.index_id

Parameters

SELECT --Parameters
  OBJECT_SCHEMA_NAME(ob.object_id) + '.' + OBJECT_NAME(ob.object_id) + '.' + par.name
  ,'schema/' + LOWER(ob.type_desc) + '/parameter'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.objects ob ON ep.major_id = ob.OBJECT_ID
  AND class = 2
INNER JOIN sys.parameters par ON ep.major_id = par.Object_id
  AND class = 2
  AND ep.minor_id = par.parameter_id

Schemas

SELECT --schemas
  sch.name
  ,'schema'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.schemas sch ON class = 3
  AND ep.major_id = SCHEMA_ID

Database

SELECT DB_NAME()
  ,''
  ,ep.name
  ,value
FROM sys.extended_properties ep
WHERE class = 0

XML Schema Collections

SELECT SCHEMA_NAME(SCHEMA_ID) + '.' + XC.name
  ,'schema/xml_Schema_collection'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.xml_schema_collections xc ON class = 10
  AND ep.major_id = xml_collection_id

Database Files

SELECT --Database Files
  df.name
  ,'database_file'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.database_files df ON class = 22
  AND ep.major_id = file_id

Data Spaces

SELECT --Data Spaces
  ds.name
  ,'dataspace'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.data_spaces ds ON class = 20
  AND ep.major_id = data_space_id

Users

SELECT --USER
  dp.name
  ,'database_principal'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.database_principals dp ON class = 4
  AND ep.major_id = dp.principal_id

Partition Function

SELECT --PARTITION FUNCTION
  pf.name
  ,'partition_function'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.partition_functions pf ON class = 21
  AND ep.major_id = pf.function_id

Remote Service Binding

SELECT --REMOTE SERVICE BINDING
  rsb.name
  ,'remote service binding'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.remote_service_bindings rsb ON class = 18
  AND ep.major_id = rsb.remote_service_binding_id

Route

SELECT --Route
  rt.name
  ,'route'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.routes rt ON class = 19
  AND ep.major_id = rt.route_id

Service

SELECT --Service
  sv.name COLLATE DATABASE_DEFAULT
  ,'service'
  ,ep.name
  ,value
FROM sys.extended_properties ep
INNER JOIN sys.services sv ON class = 17
  AND ep.major_id = sv.service_id

Contract

SELECT -- 'CONTRACT'
  svc.name
  ,'service_contract'
  ,ep.name
  ,value
FROM sys.service_contracts svc
INNER JOIN sys.extended_properties ep ON class = 16
  AND ep.major_id = svc.service_contract_id

Message Type

SELECT -- 'MESSAGE TYPE'
  smt.name
  ,'message_type'
  ,ep.name
  ,value
FROM sys.service_message_types smt
INNER JOIN sys.extended_properties ep ON class = 15
  AND ep.major_id = smt.message_type_id

Plan Guide

SELECT -- 'PLAN GUIDE' 
  pg.name
  ,'plan_guide'
  ,ep.name
  ,value
FROM sys.plan_guides pg
INNER JOIN sys.extended_properties ep ON class = 27
  AND ep.major_id = pg.plan_guide_id

Assembly

SELECT -- 'assembly'
  asy.name
  ,'assembly'
  ,ep.name
  ,value
FROM sys.assemblies asy
INNER JOIN sys.extended_properties ep ON class = 5
  AND ep.major_id = asy.assembly_id

Certificates, Asymmetric Keys, and Symmetric Keys

Note: The following SQL queries for Certificates, Asymmetric Keys, and Symmetric Keys require the `class` values to be filled in for accurate results. You can find these values in the reference table below.

--UNION ALL 
SELECT --'CERTIFICATE'
  cer.name,'certificate', ep.name,value 
FROM sys.certificates cer
INNER JOIN sys.extended_properties ep ON class=? AND ep.major_id=cer.certificate_id

UNION ALL --'ASYMMETRIC KEY'
 
SELECT amk.name,'asymmetric_key', ep.name,value  
FROM sys.asymmetric_keys amk
INNER JOIN sys.extended_properties ep ON class=? AND ep.major_id=amk.asymmetric_key_id

SELECT --'SYMMETRIC KEY'
  smk.name,'symmetric_key', ep.name,value 
FROM sys.symmetric_keys smk
INNER JOIN sys.services sv ON class=? AND ep.major_id=smk.symmetric_key_id 

Here's a table outlining the `class` values for different database items:

class tinyint Identifies the class of item on which the property exists. Can be one of the following:
0 = Database
1 = Object or column
2 = Parameter
3 = Schema
4 = Database principal
5 = Assembly
6 = Type
7 = Index
8 = User defined table type column
10 = XML schema collection
15 = Message type
16 = Service contract
17 = Service
18 = Remote service binding
19 = Route
20 = Dataspace (filegroup or partition scheme)
21 = Partition function
22 = Database file
27 = Plan guide

Additional Resources

For more detailed information, please refer to the following resources:

Saturday, April 17, 2021

Foreign Key scripts

It's helpful to maintain ready-to-use scripts for resetting database contents, including reseeding identities. Feel free to adjust these scripts to fit your specific needs.

Drop Temporary Table

IF OBJECT_ID('tempdb..#Fkey') IS NOT NULL
    DROP TABLE #Fkey;
  

Create Temporary Table with Foreign Key Information

;WITH cte AS (
    SELECT 
        fkc.constraint_column_id AS consColumn,
        fk.NAME AS foreignKeyName,
        parentSchema.name AS parentSchema,
        parentTable.NAME AS parentTableName,
        parent_col.NAME AS parentColName,
        refSchema.name AS refSchema,
        refTable.NAME AS refTableName,
        ref_col.NAME AS refColName
    FROM sys.foreign_keys fk
    INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
    INNER JOIN sys.tables parentTable ON parentTable.object_id = fkc.parent_object_id
    INNER JOIN sys.schemas parentSchema ON parentSchema.schema_id = parentTable.schema_id
    INNER JOIN sys.columns parent_col ON fkc.parent_column_id = parent_col.column_id AND parent_col.object_id = parentTable.object_id
    INNER JOIN sys.tables refTable ON refTable.object_id = fkc.referenced_object_id
    INNER JOIN sys.schemas refSchema ON refSchema.schema_id = refTable.schema_id
    INNER JOIN sys.columns ref_col ON fkc.referenced_column_id = ref_col.column_id AND ref_col.object_id = refTable.object_id
    WHERE parentTable.type = 'U' AND refTable.type = 'U'
)
SELECT DISTINCT 
    foreignKeyName,
    parentSchema,
    parentTableName,
    SUBSTRING((
        SELECT ',' + a.parentColName
        FROM cte a
        WHERE a.foreignKeyName = c.foreignKeyName
        ORDER BY a.consColumn
        FOR XML PATH('')
    ), 2, 300000) AS parentColName,
    refSchema,
    refTableName,
    SUBSTRING((
        SELECT ',' + b.refColName
        FROM cte b
        WHERE b.foreignKeyName = c.foreignKeyName
        ORDER BY b.consColumn
        FOR XML PATH('')
    ), 2, 300000) AS refColName
INTO #Fkey
FROM cte c;
  

Generate Scripts to Drop Foreign Keys

-- Generate scripts to drop existing foreign key constraints
SELECT DISTINCT 
    'IF EXISTS (SELECT * FROM sys.foreign_keys 
        WHERE object_id = OBJECT_ID(N''[' + parentSchema + '].[' + foreignKeyName + ']'') 
        AND parent_object_id = OBJECT_ID(N''[' + parentSchema + '].[' + ParentTableName + ']''))
    ALTER TABLE [' + parentSchema + '].[' + ParentTableName + '] DROP CONSTRAINT [' + foreignKeyName + ']' 
AS foreignKey_drop_script
FROM #Fkey;
  

Generate Scripts to Recreate Foreign Keys

-- Generate scripts to recreate the foreign key constraints
SELECT DISTINCT 
    'ALTER TABLE [' + parentSchema + '].[' + ParentTableName + '] WITH CHECK 
    ADD CONSTRAINT [' + foreignKeyName + '] FOREIGN KEY(' + parentColName + ') 
    REFERENCES [' + refSchema + '].[' + refTableName + '](' + refColName + ')' 
AS Add_constraints_script
FROM #Fkey;
GO
  

Additional Resources:

Monday, March 29, 2021

Get VLF count for all databases

This post explores how to retrieve information about Virtual Log Files (VLFs) within your SQL Server transaction logs. Understanding VLF distribution is crucial because a large number of VLFs can negatively impact database startup, restore, and recovery times.


What are Virtual Log Files (VLFs)?

VLFs are segments within your SQL Server transaction log. While the physical transaction log file appears as one continuous unit, SQL Server internally divides it into these smaller, manageable VLFs. You can learn more about their architecture here.


Why VLF Count Matters

An excessive number of VLFs can lead to performance degradation. When SQL Server needs to read or process the transaction log (e.g., during database startup, recovery after a crash, or restoring a backup), it has to process each VLF. More VLFs mean more overhead, extending these critical operations.


Querying VLF Information

You can use the sys.dm_db_log_info dynamic management function to inspect VLF details for your databases.

Here's a handy query to identify databases with a high VLF count, ordered from highest to lowest:

SELECT [name] AS [Database Name]
 ,[VLF Count]
FROM sys.databases AS db WITH (NOLOCK)
CROSS APPLY (
 SELECT file_id
 ,COUNT(*) AS [VLF Count]
 FROM sys.dm_db_log_info(db.database_id)
 GROUP BY file_id
 ) AS li
ORDER BY [VLF Count] DESC
OPTION (RECOMPILE);

To see the detailed VLF information for your current database, you can run:

select * from sys.dm_db_log_info(db_id())

Further Reading

For more in-depth information about sys.dm_db_log_info, refer to the official Microsoft documentation: dm_db_log_info (Transact-SQL).

Friday, March 19, 2021

Get IO warning from log

If you're managing a SQL Server instance, you know how crucial fast disk I/O is for overall database performance. When I/O operations start to slow down, it can lead to noticeable performance degradation and user frustration. Thankfully, SQL Server logs warnings when I/O operations take longer than 15 seconds, and you can easily access this information to pinpoint potential bottlenecks.

By querying the SQL Server error log, you can identify these long-running I/O warnings. This can be an invaluable first step in diagnosing disk-related performance issues, allowing you to investigate further and optimize your storage subsystem.

Here's a handy SQL script you can use to retrieve these I/O warning messages from your SQL Server error logs:

CREATE TABLE #IOWarning (LogDate datetime
 , ProcessInfo sysname
 , LogText nvarchar(1000));

INSERT INTO #IOWarning EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';
INSERT INTO #IOWarning EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';
INSERT INTO #IOWarning EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';
INSERT INTO #IOWarning EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';
INSERT INTO #IOWarning EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';
INSERT INTO #IOWarning EXEC xp_readerrorlog 5, 1, N'taking longer than 15 seconds';

SELECT LogDate, ProcessInfo, LogText
FROM #IOWarning
ORDER BY LogDate DESC;
  

How the Script Works:

  • The script first creates a temporary table named #IOWarning to store the retrieved log entries.
  • It then uses xp_readerrorlog to query the SQL Server error logs. The parameters `0, 1, N'taking longer than 15 seconds'` specifically look for the current log (0) and archived logs (1 through 5) for entries containing the phrase "taking longer than 15 seconds," which is the standard warning message for slow I/O.
  • Finally, it selects and orders the results by LogDate in descending order, showing you the most recent warnings first.

This script provides a quick way to gain insight into potential I/O performance issues. If you consistently see these warnings, it's a strong indicator that you need to investigate your disk configuration, storage array, or underlying hardware. Happy troubleshooting!

Sunday, February 7, 2021

Get input buffer information for the current database

Exploring Input Buffer Information for Non-System Sessions in SQL Server

Ever needed to peek into what all your active, non-system SQL Server sessions are actually doing? This handy SQL query allows you to retrieve input buffer information for all user sessions within the current database, giving you insight into the commands or queries they are executing.

SQL Query to Get Session Input Buffer Details


SELECT
    es.session_id,
    DB_NAME(es.database_id) AS [Database Name],
    es.login_time,
    es.cpu_time,
    es.logical_reads,
    es.memory_usage,
    es.[status],
    ib.event_info AS [Input Buffer]
FROM
    sys.dm_exec_sessions AS es WITH (NOLOCK)
CROSS APPLY
    sys.dm_exec_input_buffer(es.session_id, NULL) AS ib
WHERE
    es.database_id = DB_ID()
    AND es.session_id > 50 -- Excludes system sessions
    AND es.session_id <> @@SPID -- Excludes the current session
OPTION (RECOMPILE);

Related Commands and Resources

For quick checks, you can also use the DBCC INPUTBUFFER command:


DBCC INPUTBUFFER

For more in-depth information, check out these Microsoft documentation pages:

Thursday, February 4, 2021

Last VLF status of the current database

When you're working with SQL Server, understanding your transaction log files (VLFs) is crucial for database performance and management. This quick T-SQL snippet helps you get a snapshot of the most recent Virtual Log File (VLF) for your current database.

Understanding Your Latest VLF

This SQL query leverages the sys.dm_db_log_info dynamic management function, which provides detailed information about the virtual log files of the transaction log. By ordering the results by vlf_sequence_number in descending order and selecting only the top 1, we can quickly pinpoint the most recently created VLF.

SELECT TOP (1) DB_NAME(li.database_id) AS [Database Name]
 ,li.[file_id]
 ,li.vlf_size_mb
 ,li.vlf_sequence_number
 ,li.vlf_active
 ,li.vlf_status
FROM sys.dm_db_log_info(DB_ID()) AS li
ORDER BY vlf_sequence_number DESC
OPTION (RECOMPILE);

What the Columns Mean:

  • Database Name: The name of the database.
  • file_id: The ID of the log file.
  • vlf_size_mb: The size of the VLF in megabytes.
  • vlf_sequence_number: The sequence number of the VLF, indicating its order of creation.
  • vlf_active: Indicates if the VLF is currently active (1 = active, 0 = inactive).
  • vlf_status: The status of the VLF (e.g., 2 for active, 0 for reusable).

This query is a handy tool for database administrators looking to quickly assess the state of their transaction log and identify potential issues related to VLF fragmentation.

Friday, January 29, 2021

Find single-use, ad-hoc, and prepared queries

Ever wondered what's lurking in your SQL Server's plan cache? This handy query helps you find single-use ad-hoc and prepared statements that might be cluttering up your memory. Identifying these can be a great first step in optimizing your database performance!

SELECT TOP (50) DB_NAME(t.[dbid]) AS [Database Name]
 ,t.[text] AS [Query Text]
 ,cp.objtype AS [Object Type]
 ,cp.cacheobjtype AS [Cache Object Type]
 ,cp.size_in_bytes / 1024 AS [Plan Size in KB]
FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE cp.cacheobjtype = N'Compiled Plan'
 AND cp.objtype IN (N'Adhoc', N'Prepared')
 AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC
 ,DB_NAME(t.[dbid])
OPTION (RECOMPILE);

This query leverages two powerful Dynamic Management Views (DMVs) in SQL Server to gather its insights:

Suspect Pages table in SQL server

This table tracks pages that encountered a minor 823 error or an 824 error, listing one row per problematic page. While these pages are flagged as potentially corrupt, they might still be intact. The **event_type** column is updated once a suspect page is repaired, reflecting its new status.

SELECT 
    DB_NAME(database_id) AS [Database Name],
    [file_id],
    page_id,
    event_type,
    error_count,
    last_update_date
FROM 
    msdb.dbo.suspect_pages WITH (NOLOCK)
ORDER BY 
    database_id
OPTION (RECOMPILE);

For more details, refer to the official Microsoft documentation on suspect_pages.

Saturday, December 5, 2020

How to find SQL Server Cluster information

 How to find SQL Server Cluster information

In this post, I'll walk you through how to retrieve information about a SQL Server cluster.

SELECT SERVERPROPERTY('IsClustered'), SERVERPROPERTY('ComputerNamePhysicalNetBIOS'),
       SERVERPROPERTY('MachineName'), SERVERPROPERTY('InstanceName'), SERVERPROPERTY('ServerName')
;

WITH ClusterActiveNode AS (
    SELECT SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS NodeName, CAST('Active' AS VARCHAR(10)) AS Active
),
ClusterNodes AS (
    SELECT NodeName FROM sys.dm_os_cluster_nodes
)
SELECT b.nodename, ISNULL(active, 'Passive') AS NodeStatus
FROM ClusterNodes AS b
LEFT JOIN ClusterActiveNode AS a ON a.NodeName = b.nodename;

Machine Name: This is the name of the Windows computer where the server instance is running. If the instance is clustered, it returns the name of the virtual server for a SQL Server instance running on a Microsoft Cluster Service.
Instance Name: The name of the specific SQL Server instance the user is connected to.
Server Name: This provides both the Windows server and instance information related to a specified SQL Server instance.

The following query displays the location of the SQL Server failover cluster diagnostic log (SQL Server Error Log). This information is valuable for troubleshooting and also reveals the locations of other error and diagnostic logs.

SELECT is_enabled, [path], max_size, max_files
FROM sys.dm_os_server_diagnostics_log_configurations WITH (NOLOCK) OPTION (RECOMPILE);

To find information about your storage, you can use the query below:

/* Using In-Built Function to Identify Nodes of SQL Server Failover Cluster */
SELECT * FROM fn_virtualservernodes();
GO
EXEC XP_FIXEDDRIVES;

/* Using DMV to Identify Nodes of SQL Server Failover Cluster */
SELECT * FROM sys.dm_os_cluster_nodes;
GO
SELECT * FROM fn_servershareddrives();

/* Using DMV Function to Identify Shared Drives Used by SQL Server Failover Cluster Instance */
SELECT * FROM sys.dm_io_cluster_shared_drives;

EXEC master.dbo.xp_readerrorlog 1, 1, N'NETBIOS', NULL, NULL, NULL, N'desc';

Tuesday, December 1, 2020

Sql server Database list with Size

 

How to List Databases with Their Sizes in SQL Server

If you're managing a SQL Server instance and want to check the size of each database—including both data and log files—you can use the following query. This script retrieves all user databases, calculates the size of their data and log files in megabytes, and displays the results in descending order by data file size.

SQL Query


SELECT
    DB.name,
    SUM(CASE WHEN [type] = 0 THEN MF.size * 8 / 1024 ELSE 0 END) AS DataFileSizeMB,
    SUM(CASE WHEN [type] = 1 THEN MF.size * 8 / 1024 ELSE 0 END) AS LogFileSizeMB
FROM    sys.master_files MF
JOIN sys.databases DB ON DB.database_id = MF.database_id
WHERE DB.source_database_id IS NULL -- Exclude database snapshots
GROUP BY DB.name
ORDER BY DataFileSizeMB DESC;

Explanation

  • sys.master_files contains information about all database files, including data and log files.

  • The type column distinguishes file types: 0 for data files and 1 for log files.

  • The size is reported in 8KB pages, so multiplying by 8 and dividing by 1024 converts it to megabytes (MB).

  • Snapshots are excluded using the source_database_id IS NULL condition.

This query is useful for DBAs who want to monitor and manage database storage more effectively.

Saturday, November 14, 2020

How to find orphan database files

In this post, I will share a sample SQL query that helps identify database files that are not in use by SQL Server.

DECLARE @data_file_path VARCHAR(255)

SET @data_file_path = 'D:\\data\\MSSQL10_50.MSSQLSERVER\\MSSQL\\DATA\\'

-- Creating a temporary table to store file names from the directory.
IF object_id('tempdb..#folder') IS NOT NULL
    DROP TABLE #folder

CREATE TABLE #folder (
    cid INT identity(1, 1) PRIMARY KEY CLUSTERED,
    subdirectory VARCHAR(255),
    depth INT,
    isfile INT
)

-- Populating the temporary table with file names using xp_dirtree.
INSERT INTO #folder (
    [subdirectory],
    [depth],
    [isfile]
)
EXEC master..xp_dirtree @data_file_path, 1, 1

-- Comparing files found in the OS data file location to files linked to live databases.
-- WARNING: This does not account for detached data files. If you have detached data files, consult your DBA before cleaning up orphaned files.
SELECT 'path location' = @data_file_path,
       'orphaned data files' = subdirectory
FROM #folder
WHERE subdirectory LIKE '%df' -- Only compares .mdf, .ndf, and .ldf files
  AND subdirectory NOT IN (
        SELECT right(smf.physical_name, charindex('\\', reverse('\\' + smf.physical_name)) - 1)
        FROM sys.master_files smf
        JOIN sys.databases sd ON smf.database_id = sd.database_id
    )
ORDER BY subdirectory ASC

Sunday, September 20, 2020

How to find the missing foreign key indexes

Finding Missing Indexes on Foreign Key Relation Tables

In this article, I'm exploring how to identify missing indexes in tables with foreign key relationships.

SELECT DB_NAME() AS DBName
    , rc.Constraint_Name AS FK_Constraint
    , ccu.Table_Name AS FK_Table
    , ccu.Column_Name AS FK_Column
    , ccu2.Table_Name AS ParentTable
    , ccu2.Column_Name AS ParentColumn
    , I.Name AS IndexName
    , CASE WHEN I.Name IS NULL
        THEN 'IF NOT EXISTS (SELECT * FROM sys.indexes
                    WHERE object_id = OBJECT_ID(N''' + RC.Constraint_Schema + '.' + ccu.Table_Name + ''') 
            AND name = N''IX_' + ccu.Table_Name + '_' + ccu.Column_Name + ''') ' + '
            CREATE NONCLUSTERED INDEX IX_' + ccu.Table_Name + '_' + ccu.Column_Name + ' 
            ON ' + rc.Constraint_Schema + '.' + ccu.Table_Name + '( ' + ccu.Column_Name + ' ASC ) 
            WITH (PAD_INDEX = OFF
            ,STATISTICS_NORECOMPUTE = OFF
            ,SORT_IN_TEMPDB = ON
            ,IGNORE_DUP_KEY = OFF
            ,DROP_EXISTING = OFF, ONLINE = ON);'
        ELSE ''
    END AS SQL
FROM information_schema.referential_constraints RC
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON rc.CONSTRAINT_NAME = ccu.CONSTRAINT_NAME
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu2 ON rc.UNIQUE_CONSTRAINT_NAME = ccu2.CONSTRAINT_NAME
LEFT JOIN sys.columns c ON ccu.Column_Name = C.name
    AND ccu.Table_Name = OBJECT_NAME(C.OBJECT_ID)
LEFT JOIN sys.index_columns ic ON C.OBJECT_ID = IC.OBJECT_ID
    AND c.column_id = ic.column_id
    AND index_column_id = 1
-- index found has the foreign key
-- as the first column 
LEFT JOIN sys.indexes i ON IC.OBJECT_ID = i.OBJECT_ID
    AND ic.index_Id = i.index_Id
WHERE I.name IS NULL
ORDER BY FK_table
    ,ParentTable
    ,ParentColumn;

Other References:

Popular Posts