Showing posts with label Configuration. Show all posts
Showing posts with label Configuration. Show all posts

Saturday, December 11, 2021

Resource Governor Resource Pool information

Ever wondered about the current status of your SQL Server resource pools? This quick query provides valuable insights into their performance and memory utilization.

SELECT
    pool_id,
    [Name],
    statistics_start_time,
    min_memory_percent,
    max_memory_percent,
    max_memory_kb / 1024 AS [max_memory_mb],
    used_memory_kb / 1024 AS [used_memory_mb],
    target_memory_kb / 1024 AS [target_memory_mb],
    min_iops_per_volume,
    max_iops_per_volume
FROM
    sys.dm_resource_governor_resource_pools WITH (NOLOCK)
OPTION (RECOMPILE);

This query leverages the sys.dm_resource_governor_resource_pools dynamic management view to give you a clear picture of how your resource governor is managing your SQL Server resources.

Tuesday, September 28, 2021

SQL Server Services information

Ever wondered about the nitty-gritty details of your SQL Server services? This handy query gives you a quick overview of essential information for each service running on your server.

SELECT servicename
 ,process_id
 ,startup_type_desc
 ,status_desc
 ,last_startup_time
 ,service_account
 ,is_clustered
 ,cluster_nodename
 ,[filename]
 ,instant_file_initialization_enabled
FROM sys.dm_server_services WITH (NOLOCK)
OPTION (RECOMPILE);

This query pulls details like the **service name**, its **process ID**, how it's set to **start up** (manual, automatic, etc.), its **current status**, when it last **started**, the **account** it's running under, and whether it's part of a **cluster**. It even tells you if **Instant File Initialization** is enabled!

For more in-depth information about `sys.dm_server_services`, you can always refer to the official Microsoft documentation.



Sunday, August 29, 2021

SQL Server NUMA Node information

This query provides valuable insights into your NUMA (Non-Uniform Memory Access) nodes, showing their composition and how much load they're handling. It helps you understand the distribution of resources and activity across your system's memory architecture.

SELECT node_id
 ,node_state_desc
 ,memory_node_id
 ,processor_group
 ,cpu_count
 ,online_scheduler_count
 ,idle_scheduler_count
 ,active_worker_count
 ,avg_load_balance
 ,resource_monitor_state
FROM sys.dm_os_nodes WITH (NOLOCK)
WHERE node_state_desc <> N'ONLINE DAC'
OPTION (RECOMPILE);

After running this, you'll want to verify that an equal number of schedulers are assigned to each NUMA node. This is especially important for physical or virtual machines with more than four sockets or over 24 physical cores, as balanced scheduler distribution can significantly impact performance.

For more detailed information, check out these resources:

Saturday, August 28, 2021

Get Server properties

Discovering SQL Server Instance Details with SERVERPROPERTY

Ever needed to quickly grab essential information about your SQL Server instance? The `SERVERPROPERTY` function is your best friend! It allows you to retrieve a wide range of details, from server names and versions to specific configurations like collation and default paths. Below is a comprehensive SQL query that leverages `SERVERPROPERTY` to pull numerous valuable insights about your SQL Server environment.

SELECT SERVERPROPERTY('MachineName') AS val, 'Machine Name' AS Descr
UNION ALL SELECT SERVERPROPERTY('ServerName'), 'Server Name'
UNION ALL SELECT SERVERPROPERTY('InstanceName'), 'Instance'
UNION ALL SELECT SERVERPROPERTY('IsClustered'), 'IsClustered'
UNION ALL SELECT SERVERPROPERTY('ComputerNamePhysicalNetBIOS'), 'Computer Name Physical NetBIOS'
UNION ALL SELECT SERVERPROPERTY('Edition'), 'Edition'
UNION ALL SELECT SERVERPROPERTY('ProductLevel'), 'Product Level (What servicing branch (RTM/SP/CU))'
UNION ALL SELECT SERVERPROPERTY('ProductUpdateLevel'), 'Product Update Level (Within a servicing branch, what CU# is applied)'
UNION ALL SELECT SERVERPROPERTY('ProductVersion'), 'Product Version'
UNION ALL SELECT SERVERPROPERTY('ProductMajorVersion'), 'Product Major Version'
UNION ALL SELECT SERVERPROPERTY('ProductMinorVersion'), 'Product Minor Version'
UNION ALL SELECT SERVERPROPERTY('ProductBuild'), 'Product Build'
UNION ALL SELECT SERVERPROPERTY('ProductBuildType'), 'Product Build Type ( Is this a GDR or OD hotfix (NULL if on a CU build))'
UNION ALL SELECT SERVERPROPERTY('ProductUpdateReference'), 'Product Update Reference (KB article number that is applicable for this build)'
UNION ALL SELECT SERVERPROPERTY('ProcessID'), 'ProcessID'
UNION ALL SELECT SERVERPROPERTY('Collation'), 'Collation'
UNION ALL SELECT SERVERPROPERTY('IsFullTextInstalled'), 'IsFullTextInstalled'
UNION ALL SELECT SERVERPROPERTY('IsIntegratedSecurityOnly'), 'IsIntegratedSecurityOnly'
UNION ALL SELECT SERVERPROPERTY('FilestreamConfiguredLevel'), 'FilestreamConfiguredLevel'
UNION ALL SELECT SERVERPROPERTY('IsHadrEnabled'), 'IsHadrEnabled'
UNION ALL SELECT SERVERPROPERTY('HadrManagerStatus'), 'HadrManagerStatus'
UNION ALL SELECT SERVERPROPERTY('InstanceDefaultDataPath'), 'InstanceDefaultDataPath'
UNION ALL SELECT SERVERPROPERTY('InstanceDefaultLogPath'), 'InstanceDefaultLogPath'
UNION ALL SELECT SERVERPROPERTY('BuildClrVersion'), 'Build CLR Version'
UNION ALL SELECT SERVERPROPERTY('IsXTPSupported'), 'IsXTPSupported'
UNION ALL SELECT SERVERPROPERTY('IsPolybaseInstalled'), 'IsPolybaseInstalled'
UNION ALL SELECT SERVERPROPERTY('IsAdvancedAnalyticsInstalled'), 'IsRServicesInstalled'
  

This query provides a detailed overview of your SQL Server setup, making it incredibly useful for inventory, troubleshooting, or just getting a quick snapshot of your environment.

Further Reading

For a complete and in-depth understanding of all the properties available with `SERVERPROPERTY`, check out the official Microsoft documentation.

Saturday, August 7, 2021

SQL Socket & Core information

This post will show you how to find out the **socket, physical core, and logical core counts** directly from your **SQL Server Error log**. This information is crucial for verifying your SQL Server licensing model.

EXEC sys.xp_readerrorlog 0, 1, N'detected', N'socket';

Running the command above helps you quickly confirm your SQL Server's configuration and ensure it aligns with your licensing.

Wednesday, July 28, 2021

List of all global trace flags that are enabled

Ever wondered which global trace flags are active in your SQL Server environment? You can easily discover them using the following command:

DBCC TRACESTATUS (-1);
  

This command reveals all currently enabled global trace flags. For instance, you might encounter some common ones like:

  • TF 3226: This flag is a neat trick to keep your SQL Server Error Log cleaner by suppressing messages for successful database backups.
  • TF 6534: If you're working with spatial data, this flag is your friend! It enables the use of native code, which can significantly boost performance.
  • TF 7745: Important for maintaining data integrity, this flag prevents Query Store data from being written to disk during a failover or shutdown.

To enable a specific trace flag, simply use the DBCC TRACEON command, replacing <Ftrace flag> with the desired flag number:

DBCC TRACEON <Ftrace flag>
  

For a comprehensive understanding of SQL Server trace flags and their functionalities, refer to the official Microsoft documentation.

Monday, June 28, 2021

SQL Configuration Values

When working with SQL Server, understanding its configuration settings is crucial for optimal performance and troubleshooting. The sys.configurations system catalog view provides a wealth of information about all the server-wide configuration options. Here's a quick way to view all of them:

SELECT name
 ,value
 ,value_in_use
 ,minimum
 ,maximum
 ,[description]
 ,is_dynamic
 ,is_advanced
FROM sys.configurations WITH (NOLOCK)
ORDER BY name
OPTION (RECOMPILE);

This query gives you a comprehensive list, including the name of each configuration, its current value, the value actually in use, its minimum and maximum possible settings, a description, and whether it's dynamic (can be changed without restarting the server) or advanced (should only be changed by experienced administrators).

While reviewing all configurations is helpful, you'll often want to check specific settings that are critical for performance or common troubleshooting scenarios. Here are some examples of important configurations and their typical recommended values:

select * from  sys.configurations WITH (NOLOCK) where name like 'automatic soft-NUMA%'  --should be 0 in most cases
select * from  sys.configurations WITH (NOLOCK) where name like 'backup checksum%'  --should be 1
select * from  sys.configurations WITH (NOLOCK) where name like 'backup compression default%'  --should be 1 in most cases
select * from  sys.configurations WITH (NOLOCK) where name like 'clr enabled%'  --only enable if it is needed
select * from  sys.configurations WITH (NOLOCK) where name like 'cost threshold for parallelism%'  --(depends on your workload)
select * from  sys.configurations WITH (NOLOCK) where name like 'lightweight%'  --should be zero
select * from  sys.configurations WITH (NOLOCK) where name like 'max degree of parallelism%'  --depends on your workload and hardware
select * from  sys.configurations WITH (NOLOCK) where name like 'max server memory%'  --set to an appropriate value, not the default
select * from  sys.configurations WITH (NOLOCK) where name like 'optimize for ad hoc workloads'  --should be 1
select * from  sys.configurations WITH (NOLOCK) where name like 'priority boost%'  --should be zero
select * from  sys.configurations WITH (NOLOCK) where name like 'remote admin connections%'  --should be 1
select * from  sys.configurations WITH (NOLOCK) where name like 'tempdb metadata memory-optimized%'  --0 by default, some workloads may benefit by enabling

Remember that the "best" setting for some of these options, like cost threshold for parallelism and max degree of parallelism, can vary significantly depending on your specific workload and server hardware. Always test changes in a development environment before applying them to production.

For more in-depth details on each configuration option, you can always refer to the official Microsoft documentation for sys.configurations.

SQL Information

Ever wonder about the specific build and version of your SQL Server instance? You can easily find out using this simple SQL query:

SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];

Speaking of versions, here's a detailed look at the various builds of **SQL Server 2019**, including their release dates and links to relevant Microsoft Knowledge Base (KB) articles:

Build Description Release Date
15.0.1000.34 CTP 2.0 9/24/2018
15.0.1100.94 CTP 2.1 11/7/2018
15.0.1200.24 CTP 2.2 12/6/2018
15.0.1300.359 CTP 2.3 3/1/2019
15.0.1400.75 CTP 2.4 3/26/2019
15.0.1500.28 CTP 2.5 4/23/2019
15.0.1600.8 CTP 3.0 5/22/2019
15.0.1700.37 CTP 3.1 6/26/2019
15.0.1800.32 CTP 3.2 7/24/2019
15.0.1900.25 RC1/RC1 Refresh 8/29/2019
15.0.2000.5 RTM 11/4/2019
15.0.2070.41 GDR1 11/4/2019

For more comprehensive information, you can refer to these official Microsoft resources:

Saturday, June 5, 2021

Find Your Database's Query Store Settings

SQL query that pulls data from the sys.database_query_store_options view.

This query is likely related to monitoring or troubleshooting the SQL Server Query Store settings.

Here's a quick breakdown of the query:


SELECT
  actual_state_desc,               -- Description of the current state of the Query Store
  desired_state_desc,              -- Description of the desired state of the Query Store
  interval_length_minutes,         -- The length of the interval in minutes for Query Store data collection
  current_storage_size_mb,         -- The current size of the Query Store in MB
  max_storage_size_mb,             -- The maximum storage size for the Query Store in MB
  query_capture_mode_desc,         -- The capture mode for query plans and runtime statistics
  size_based_cleanup_mode_desc     -- The cleanup mode used when managing Query Store size
FROM sys.database_query_store_options WITH (NOLOCK)
OPTION (RECOMPILE);

Key Points:

  • WITH (NOLOCK): This hint tells SQL Server to perform a dirty read, meaning it doesn't acquire shared locks and can read uncommitted data. This can speed up queries but might return inconsistent results if data is being modified.
  • OPTION (RECOMPILE): Forces SQL Server to recompile the query plan each time it's run, which could be useful for queries with varying parameters but may add overhead.

Friday, January 29, 2021

Get database file info

Ever wondered where your SQL Server database files are actually stored? This handy query helps you quickly find the **file names and physical paths for all user and system databases** on your instance. It's a great way to get an overview of your database file locations and properties.

SELECT DB_NAME([database_id]) AS [Database Name]
 ,[file_id]
 ,[name]
 ,physical_name
 ,[type_desc]
 ,state_desc
 ,is_percent_growth
 ,growth
 ,CONVERT(BIGINT, growth / 128.0) AS [Growth in MB]
 ,CONVERT(BIGINT, size / 128.0) AS [Total Size in MB]
 ,max_size
FROM sys.master_files WITH (NOLOCK)
ORDER BY DB_NAME([database_id])
 ,[file_id]
OPTION (RECOMPILE);

This query pulls information from the sys.master_files catalog view, which provides details about the files in your SQL Server instance.

How to Get TempDB Files Count in SQL Server

Ever wonder how many data files your tempdb database is currently using? You can quickly find this information by querying the SQL Server error log. This can be helpful for monitoring your SQL Server instance's configuration and performance.

-- Get number of data files in tempdb database (Query 24) (TempDB Data Files)
EXEC sys.xp_readerrorlog 0, 1, N'The tempdb database has';
  

The above SQL snippet uses the xp_readerrorlog extended stored procedure to filter the error log for messages related to the number of tempdb data files. This provides a direct way to see the current count without needing to delve into system views.

---

More SQL Server Insights

Here are some other valuable resources and tips for managing your SQL Server environment:

Reading Specific Errors with Temporary Tables

For more advanced error log analysis, check out this post on how to read specific errors using temporary tables. This technique offers greater flexibility in parsing and analyzing log data.

Retrieving I/O Warnings from the Log

Input/Output (I/O) warnings can be crucial indicators of performance bottlenecks. Learn how to retrieve I/O warnings directly from your SQL Server log to proactively address potential issues.

Understanding SQL Socket Core Information

For a deeper dive into your SQL Server's configuration, exploring SQL socket core information can provide valuable insights into how your server is utilizing its CPU resources.

Sunday, November 29, 2020

How to add DB2 as a linked server in SQL

 How to add DB2 as a linked server  in SQL

In this post, I will demonstrate how to add a new linked server in SQL Server.

-- Creating the Linked Server: [AS400DB]
EXEC master.dbo.sp_addlinkedserver 
    @server = N'AS400DB',
    @srvproduct = N'AS400',
    @provider = N'IBMDASQL',
    @datasrc = N'10.0.1.1';

-- Setting up the linked server login
EXEC master.dbo.sp_addlinkedsrvlogin 
    @rmtsrvname = N'AS400DB',
    @useself = N'False',
    @locallogin = NULL,
    @rmtuser = N'MyUser',
    @rmtpassword = '########';
GO

-- Configuring server options
EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'collation compatible',
    @optvalue = N'false';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'data access',
    @optvalue = N'true';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'dist',
    @optvalue = N'false';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'pub',
    @optvalue = N'false';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'rpc',
    @optvalue = N'true';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'rpc out',
    @optvalue = N'true';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'sub',
    @optvalue = N'false';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'connect timeout',
    @optvalue = N'0';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'collation name',
    @optvalue = NULL;
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'lazy schema validation',
    @optvalue = N'false';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'query timeout',
    @optvalue = N'0';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'use remote collation',
    @optvalue = N'true';
GO

EXEC master.dbo.sp_serveroption 
    @server = N'AS400DB',
    @optname = N'remote proc transaction promotion',
    @optvalue = N'true';
GO

This script will successfully configure the linked server, allowing you to connect to an AS400 database from SQL Server. Ensure that all server names, IP addresses, and credentials are accurate before executing.

Saturday, November 21, 2020

How to add oracle as a linked server in SQL server

In this post, I will guide you through the steps to add a new Oracle linked server in SQL Server.

/****** Linked Server Creation for [PAYROLL] ******/
EXEC master.dbo.sp_addlinkedserver @server = N'PAYROLL'
   ,@srvproduct = N'MSDAORA'
   ,@provider = N'MSDAORA'
   ,@datasrc = N'pay4win20'  -- pay4win20 is the service name, payroll is the server name, and MSDAORA is the Oracle driver name

EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'PAYROLL'
   ,@useself = N'False'
   ,@locallogin = NULL
   ,@rmtuser = N'system'
   ,@rmtpassword = '########'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'collation compatible'
   ,@optvalue = N'false'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'data access'
   ,@optvalue = N'true'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'dist'
   ,@optvalue = N'false'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'pub'
   ,@optvalue = N'false'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'rpc'
   ,@optvalue = N'false'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'rpc out'
   ,@optvalue = N'false'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'sub'
   ,@optvalue = N'false'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'connect timeout'
   ,@optvalue = N'0'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'collation name'
   ,@optvalue = NULL
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'lazy schema validation'
   ,@optvalue = N'false'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'query timeout'
   ,@optvalue = N'0'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'use remote collation'
   ,@optvalue = N'true'
GO

EXEC master.dbo.sp_serveroption @server = N'PAYROLL'
   ,@optname = N'remote proc transaction promotion'
   ,@optvalue = N'true'
GO

Additional References:

DB2 as a Linked Server
Linked Server with a Different Name

Saturday, October 10, 2020

How to work with a certificate in SQL Server

How to work with a certificate in SQL Server

This SQL command adds a certificate to a SQL Server database.

To perform this action, you need to have the CREATE CERTIFICATE permission on the database. It's important to note that only Windows logins, SQL Server logins, and application roles can own certificates. Groups and other roles are not allowed to own certificates.

-- Create a self-signed certificate
CREATE CERTIFICATE selfsigned
   ENCRYPTION BY PASSWORD = 'selfsigned2439587y'  
   WITH SUBJECT = 'Testing self-signed Records',
   EXPIRY_DATE = '20251031';
-- Restoring the certificate involves using the same process as creating a new certificate.
create certificate MySalaryCert
from file = N'c:\\Encryption\\MyCerti.cer'
with private key
  ( file = N'c:\\Encryption\\MyCerti.pvk'
  , decryption by password = N'hiMaNshu#paTel#dBa'
   );
CREATE CERTIFICATE MySalaryCert  
    FROM EXECUTABLE FILE = 'c:\\MySalaryCert.dll';  
GO
CREATE ASSEMBLY MySalaryCert  
    FROM 'c:\\MySalaryCert.dll'   
    WITH PERMISSION_SET = SAFE;  
GO  
CREATE CERTIFICATE MySalaryCert FROM ASSEMBLY MySalaryCert;  
GO
-- The following query displays the details of the certificate, including the public and private key information:
SELECT
  name,
  certificate_id,
  pvt_key_encryption_type_desc,
  subject,
  expiry_date,
  start_date,
  thumbprint,
  pvt_key_last_backup_date
FROM sys.certificates;

For more information, refer to the following resources:

Microsoft Docs: CREATE CERTIFICATE (Transact-SQL)

MSSQLTips: How to Configure SSL Encryption in SQL Server

Sunday, September 27, 2020

Implementing Dynamic Data Masking in SQL Server

Implementing Dynamic Data Masking in SQL Server

Introduction to Dynamic Data Masking (DDM)

Dynamic Data Masking (DDM) is a technique that restricts access to sensitive data by masking it for users without the required privileges. This approach makes it easier to design and implement security measures in your applications, ensuring that sensitive information is protected while allowing authorized users to access necessary data.

Permissions Required for Dynamic Data Masking

To create a table with dynamic data masking, you don’t need special permissions beyond the standard CREATE TABLE and ALTER permissions for the schema. However, there are additional permissions needed for manipulating the data masks.

  1. Modifying Masks: You need the ALTER ANY MASK permission, in addition to ALTER on the table.
  2. Viewing Data: Users with SELECT permissions can see only the masked data. Assign UNMASK permission to allow viewing unmasked data.
  3. Control Permissions: The CONTROL permission includes both ALTER ANY MASK and UNMASK.

Limitations and Restrictions of Data Masking

There are some column types that cannot be masked, including:

  • Encrypted columns (Always Encrypted)
  • FILESTREAM columns
  • Sparse columns that are part of a column set
  • Computed columns: If a computed column depends on a masked column, it will show masked data.
  • Columns involved in a FULLTEXT index

Example: Creating a Table with a Mask

You can create a table with dynamic data masking as shown below:

CREATE TABLE MembershipMask  
(
  MemberID int IDENTITY PRIMARY KEY,  
  FirstName varchar(100) MASKED WITH (FUNCTION = 'partial(1,"XXXXXXX",0)') NULL,  
  LastName varchar(100) NOT NULL,  
  Phone varchar(12) MASKED WITH (FUNCTION = 'default()') NULL,  
  Email varchar(100) MASKED WITH (FUNCTION = 'email()') NULL  
);

Insert sample data:

INSERT MembershipMask (FirstName, LastName, Phone, Email) VALUES  
('Vipul', 'Bhatt', '456.123.4567', 'Vipul@Himanshupatel.in'),  
('Dev', 'Shah', '456.123.3333', 'Dev@Himanshupatel.in'),  
('Raj', 'Patel', '555.123.4569', 'raj@Himanshupatel.in');

Querying the table will display masked data:

SELECT * FROM MembershipMask;

Example output for a user with SELECT permission:

MemberID FirstName LastName Phone Email
1        VXXXXXXX  Bhatt     xxxx  VXXX@XXXX.com
2        DXXXXXXX  Shah      xxxx  DXXX@XXXX.com
3        RXXXXXXX  Patel     xxxx  RXXX@XXXX.com

Viewing the Data Masking Definition

Use the following query:

SELECT TBLS.name AS TableName, MC.NAME AS ColumnName, MC.is_masked AS IsMasked, MC.masking_function AS MaskFunction  
FROM sys.masked_columns AS MC  
JOIN sys.tables AS TBLS ON MC.object_id = TBLS.object_id  
WHERE is_masked = 1;

Dropping a Mask

To remove a mask from a column:

ALTER TABLE Membership  
ALTER COLUMN LastName DROP MASKED;

Adding or Editing a Mask on an Existing Column

ALTER TABLE Membership  
ALTER COLUMN LastName ADD MASKED WITH (FUNCTION = 'partial(2,"XXX",0)');

Granting and Revoking Mask Permissions

GRANT UNMASK TO TestUserins;
GO
REVOKE UNMASK FROM TestUserins;
GO

Implementing Partial Masking

To reveal only the last 4 digits of a national ID number:

ALTER TABLE EmpInfo  
ALTER COLUMN NatID NVARCHAR(15)  
MASKED WITH (FUNCTION = 'partial(0, "xxxxx", 4)') NOT NULL;  
-- e.g., 716374314 becomes xxxxx4314

Implementing Random Masking

To mask a monetary value within a range:

ALTER TABLE EmpInfo  
ALTER COLUMN SalesYTD MONEY  
MASKED WITH (FUNCTION = 'random(101, 999)') NOT NULL;

Further Reading

For more information, refer to the official documentation:

Microsoft Docs on Dynamic Data Masking

Saturday, September 26, 2020

Database Email and system objects

Database Email and system objects


Database Mail allows your database applications to send emails to users. These emails can include query results and files from your network.

Database Mail operates with two configuration objects: these allow you to set up the necessary settings for sending emails from your database applications or the SQL Server Agent.

Database Mail Design

Database Mail Accounts

A Database Mail account stores the details used by Microsoft SQL Server to send emails through an SMTP server. Each account is linked to a specific email server.

Create a New Database Mail Account with SMTP Details

sysmail_add_account_sp  [ @account_name = ] 'account_name',  
    [ @email_address = ] 'email_address' ,  
    [ [ @display_name = ] 'display_name' , ]  
    [ [ @replyto_address = ] 'replyto_address' , ]  
    [ [ @description = ] 'description' , ]  
    [ @mailserver_name = ] 'server_name'  
    [ , [ @mailserver_type = ] 'server_type' ]  
    [ , [ @port = ] port_number ]  
    [ , [ @username = ] 'username' ]  
    [ , [ @password = ] 'password' ]  
    [ , [ @use_default_credentials = ] use_default_credentials ]  
    [ , [ @enable_ssl = ] enable_ssl ]  
    [ , [ @account_id = ] account_id OUTPUT ]

Database Mail Profiles

A Database Mail profile is a group of related Database Mail accounts. Applications that send mail via Database Mail should specify a profile rather than individual accounts.

Profiles also allow database administrators to manage email access. Users need to be a member of the DatabaseMailUserRole to send email via Database Mail.

Profiles can either be public or private.

Create a New Database Mail Profile

sysmail_add_profile_sp [ @profile_name = ] 'profile_name'  
    [ , [ @description = ] 'description' ]  
    [ , [ @profile_id = ] new_profile_id OUTPUT ]

Add an Account to a Database Mail Profile

After creating a Database Account with sysmail_add_account_sp and a Database Profile with sysmail_add_profile_sp, you can use sysmail_add_profileaccount_sp to associate them.

Database Mail Profile Account
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp  
    @profile_name = 'AdventureWorks Administrator',  
    @account_name = 'Audit Account',  
    @sequence_number = 1 ;

Retrieve Database Mail Configuration

sysmail_help_configure_sp
sysmail_help_principalprofile_sp 
sysmail_help_profile_sp
sysmail_help_profileaccount_sp

Set Database Mail Configuration

The sysmail_configure_sp stored procedure modifies configuration settings for Database Mail at the SQL Server instance level.

Parameter NameValueDescription
AccountRetryAttempts1Number of retry attempts for a mail server
AccountRetryDelay60Delay between retry attempts
DatabaseMailExeMinimumLifeTime600Minimum process lifetime (seconds)
DefaultAttachmentEncodingMIMEDefault attachment encoding type
LoggingLevel2Logging level for Database Mail (normal - 1, extended - 2, verbose - 3)
MaxFileSize1000000Maximum file size for attachments
ProhibitedExtensionsexe,dll,vbs,jsExtensions not allowed in email attachments
sysmail_configure_sp [ [ @parameter_name = ] 'parameter_name' ]  
    [ , [ @parameter_value = ] 'parameter_value' ]  
    [ , [ @description = ] 'description' ]

Send an Email Using Database Mail

This procedure sends an email with options for attaching files or query results.

sp_send_dbmail [ [ @profile_name = ] 'profile_name' ]  
    [ , [ @recipients = ] 'recipient_email' ]  
    [ , [ @copy_recipients = ] 'cc_email' ]  
    [ , [ @blind_copy_recipients = ] 'bcc_email' ]  
    [ , [ @from_address = ] 'sender_email' ]  
    [ , [ @reply_to = ] 'reply_to_email' ]  
    [ , [ @subject = ] 'email_subject' ]  
    [ , [ @body = ] 'email_body' ]  
    [ , [ @body_format = ] 'html' ]  
    [ , [ @importance = ] 'high' ]  
    [ , [ @sensitivity = ] 'normal' ]  
    [ , [ @file_attachments = ] 'file_path' ]  
    [ , [ @query = ] 'sql_query' ]  
    [ , [ @execute_query_database = ] 'database_name' ]  
    [ , [ @attach_query_result_as_file = ] 1 ]  
    [ , [ @query_attachment_filename = ] 'file_name' ]  
    [ , [ @query_result_separator = ] ',' ]  
    [ , [ @exclude_query_output = ] 0 ]  
    [ , [ @append_query_error = ] 1 ]  
    [ , [ @query_no_truncate = ] 1 ]  
    [ , [ @query_result_no_padding = ] 1 ]  
    [ , [ @mailitem_id = ] mailitem_id ] [ OUTPUT ]

Enable Database Mail

sp_configure 'show advanced', 1; 
GO
RECONFIGURE;
GO

sp_configure 'Database Mail XPs', 1;
GO
RECONFIGURE
GO

Troubleshooting queries:

select * from msdb.dbo.sysmail_sentitems
select * from msdb.dbo.sysmail_unsentitems
select * from msdb.dbo.sysmail_faileditems
SELECT * FROM msdb.dbo.sysmail_event_log;

SELECT [sysmail_server].[account_id],
       [sysmail_account].[name] AS [Account Name],
       [servertype],
       [servername] AS [SMTP Server Address],
       [Port]
FROM [msdb].[dbo].[sysmail_server]
     INNER JOIN [msdb].[dbo].[sysmail_account] ON [sysmail_server].[account_id] = [sysmail_account].[account_id];

SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb';
GO
SELECT * FROM sys.configurations WHERE name = 'Database Mail XPs'
GO

SELECT * 
FROM msdb.dbo.sysmail_profileaccount pa 
INNER JOIN msdb.dbo.sysmail_profile p ON pa.profile_id = p.profile_id 
INNER JOIN msdb.dbo.sysmail_account a ON pa.account_id = a.account_id

SMTP server details for co

Saturday, August 8, 2020

Find Server property using TSQL code

Retrieving SQL Server Information Using T-SQL

In this article, we will discuss how to retrieve information about your installed SQL Server instance using a T-SQL query that interacts with internal system objects. This query can provide various details, such as the service account, paths, configuration settings, and much more.

Query Overview

The following T-SQL query retrieves multiple configuration settings and properties from SQL Server. It covers information such as the server's version, instance details, backup paths, and various registry settings. This is useful for system administrators and those who need to audit or document SQL Server environments.

The query returns a result in two columns: one with the name of the configuration setting and the other with its value.

Query Explanation

The query starts by declaring a series of variables that will hold the registry paths and values related to SQL Server configuration.


DECLARE @HkeyLocal NVARCHAR(18),
        @ServicesRegPath NVARCHAR(34),
        @SqlServiceRegPath SYSNAME,
        @BrowserServiceRegPath SYSNAME,
        @MSSqlServerRegPath NVARCHAR(31),
        @InstanceNamesRegPath NVARCHAR(59),
        @InstanceRegPath SYSNAME,
        @SetupRegPath SYSNAME,
        @NpRegPath SYSNAME,
        @TcpRegPath SYSNAME,
        @RegPathParams SYSNAME,
        @FilestreamRegPath SYSNAME;

The paths for various registry keys related to SQL Server configuration are then set:


SELECT @HkeyLocal = N'HKEY_LOCAL_MACHINE';

-- Instance-based paths
SELECT @MSSqlServerRegPath = N'SOFTWARE\\Microsoft\\MSSQLServer';
SELECT @InstanceRegPath = @MSSqlServerRegPath + N'\\MSSQLServer';
SELECT @FilestreamRegPath = @InstanceRegPath + N'\\Filestream';
SELECT @SetupRegPath = @MSSqlServerRegPath + N'\\Setup';
SELECT @RegPathParams = @InstanceRegPath + '\\Parameters';

-- Services
SELECT @ServicesRegPath = N'SYSTEM\\CurrentControlSet\\Services';
SELECT @SqlServiceRegPath = @ServicesRegPath + N'\\MSSQLSERVER';
SELECT @BrowserServiceRegPath = @ServicesRegPath + N'\\SQLBrowser';

-- InstanceId setting
SELECT @InstanceNamesRegPath = N'SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL';

-- Network settings
SELECT @NpRegPath = @InstanceRegPath + N'\\SuperSocketNetLib\\Np';
SELECT @TcpRegPath = @InstanceRegPath + N'\\SuperSocketNetLib\\Tcp';

Fetching Configuration Details

The query then retrieves various configuration values using the xp_instance_regread extended stored procedure. Some of the configuration details include:

  • Audit level
  • Number of error logs
  • Login mode
  • Mail profile
  • Backup directory

For example, the following code fetches the audit level:


DECLARE @SmoAuditLevel INT;
EXEC master.dbo.xp_instance_regread @HkeyLocal, @InstanceRegPath, N'AuditLevel', @SmoAuditLevel OUTPUT;

File Paths and Error Logs

The query continues by retrieving file paths for the master database, error logs, and other important system directories:


DECLARE @MasterPath NVARCHAR(512),
        @LogPath NVARCHAR(512),
        @ErrorLog NVARCHAR(512),
        @ErrorLogPath NVARCHAR(512);

SELECT @MasterPath = SUBSTRING(physical_name, 1, LEN(physical_name) - CHARINDEX('\\', REVERSE(physical_name)))
FROM master.sys.database_files WHERE name = N'master';

SELECT @LogPath = SUBSTRING(physical_name, 1, LEN(physical_name) - CHARINDEX('\\', REVERSE(physical_name)))
FROM master.sys.database_files WHERE name = N'mastlog';

SELECT @ErrorLog = CAST(SERVERPROPERTY(N'errorlogfilename') AS NVARCHAR(512));
SELECT @ErrorLogPath = SUBSTRING(@ErrorLog, 1, LEN(@ErrorLog) - CHARINDEX('\\', REVERSE(@ErrorLog)));

Extracting Additional Information

The query also retrieves additional server and instance details, including the service account name, whether named pipes and TCP are enabled, and more.


DECLARE @ServiceAccount NVARCHAR(512);
EXEC master.sys.xp_instance_regread @HkeyLocal, @SqlServiceRegPath, N'ObjectName', @ServiceAccount OUTPUT;

DECLARE @NamedPipesEnabled INT;
EXEC master.dbo.xp_instance_regread @HkeyLocal, @NpRegPath, N'Enabled', @NamedPipesEnabled OUTPUT;

DECLARE @TcpEnabled INT;
EXEC master.sys.xp_instance_regread @HkeyLocal, @TcpRegPath, N'Enabled', @TcpEnabled OUTPUT;

Retrieving Server and Instance Properties

The final output includes several important properties, such as the version of SQL Server, the server collation, and whether SQL Server is clustered:


SELECT
  SERVERPROPERTY(N'ProductVersion') AS [VersionString],
  CAST(SERVERPROPERTY(N'Edition') AS SYSNAME) AS [Edition],
  CAST(SERVERPROPERTY(N'ProductLevel') AS SYSNAME) AS [ProductLevel],
  SERVERPROPERTY('Collation') AS [Collation],
  CAST(SERVERPROPERTY('IsClustered') AS BIT) AS [IsClustered];

Query Result

The query outputs a list of configuration names along with their corresponding values. Here is an example of the result structure:

  • Audit Level: 1
  • Number of Error Logs: 10
  • Login Mode: 2
  • Mail Profile: NULL
  • Backup Directory: C:\Backup

Conclusion

This T-SQL query is a valuable tool for retrieving SQL Server configuration details from system registry entries and properties. By executing this query, administrators can gain insight into the SQL Server instance’s configuration without needing to manually inspect the system or configuration files.

Availability group fail-over

Forced Manual Failover with Data Loss (2-step Process)

To force a failover with potential data loss, connect to the SQL Server instance where the secondary replica is hosted, and execute the following command:

ALTER AVAILABILITY GROUP [ag1] FORCE_FAILOVER_ALLOW_DATA_LOSS;

Once the original primary replica recovers, it will try to assume the primary role. To ensure the previous primary becomes secondary again, run the command below on that instance:

ALTER AVAILABILITY GROUP [ag1] SET (ROLE = SECONDARY);

Steps to Manually Failover Without Data Loss:

1. First, configure the target secondary replica to use SYNCHRONOUS_COMMIT mode:

ALTER AVAILABILITY GROUP [ag1]
     MODIFY REPLICA ON N''
     WITH (AVAILABILITY_MODE = SYNCHRONOUS_COMMIT);

2. To verify that active transactions are committed to the primary and at least one synchronous secondary replica, run the following query:

SELECT ag.name, drs.database_id, drs.group_id, drs.replica_id,
   drs.synchronization_state_desc, ag.sequence_number
FROM sys.dm_hadr_database_replica_states drs, sys.availability_groups ag
WHERE drs.group_id = ag.group_id;

3. Update the REQUIRED_SYNCHRONIZED_SECONDARIES_TO_COMMIT setting to 1:

ALTER AVAILABILITY GROUP [ag1]
     SET (REQUIRED_SYNCHRONIZED_SECONDARIES_TO_COMMIT = 1);

4. Offline the primary replica in preparation for the role change:

ALTER AVAILABILITY GROUP [ag1] OFFLINE;

5. Promote the target secondary replica to the primary role:

ALTER AVAILABILITY GROUP ag1 FORCE_FAILOVER_ALLOW_DATA_LOSS;

6. Change the role of the previous primary replica to SECONDARY. Run this on the SQL Server instance hosting the previous primary replica:

ALTER AVAILABILITY GROUP [ag1] SET (ROLE = SECONDARY);

For more information, check out this resource:

Check the Writable Copy

Additional reference: Manual SQL Server Availability Group Failover

Saturday, July 25, 2020

How Find SQL Server collation

How to Find SQL Server Collation

Collations in SQL Server determine the sorting rules, case sensitivity, and accent sensitivity for your data. They play a crucial role when working with character data types like char and varchar, as they define the code page and the corresponding characters that can be represented.

Case Sensitivity

Case sensitivity refers to whether uppercase and lowercase characters are treated as distinct. For example, if the letters "A" and "a" (or "B" and "b") are considered different, the collation is case-sensitive. Computers differentiate between these letters using their ASCII values: "A" has an ASCII value of 65, while "a" has an ASCII value of 97. Similarly, "B" is 66, and "b" is 98.

Accent Sensitivity

Accent sensitivity determines whether characters with accents are considered different from their non-accented counterparts. For example, if "a" and "á" or "o" and "ó" are treated as the same, the collation is accent-insensitive. However, when treated differently, it is accent-sensitive. This distinction is based on the ASCII values of characters: "a" has a value of 97, while "á" has a value of 225; "o" is 111, and "ó" is 243.

Kana Sensitivity

Kana sensitivity occurs when Japanese kana characters, Hiragana and Katakana, are treated as distinct. When these characters are considered different in sorting, it is referred to as kana-sensitive collation.

Width Sensitivity

Width sensitivity refers to how single-byte characters (half-width) and their double-byte counterparts (full-width) are treated. When these characters are considered distinct, the collation is width-sensitive.

SQL Queries for Collation Insights

Here are a few SQL queries you can use to inspect and work with collations in SQL Server:

  1. View Columns with Collations:

    This query retrieves the schema, table, column names, and their respective collation names:

    
    SELECT s.name AS 'Schema_Name', t.name AS Table_Name,
           c.name AS Column_Name, c.collation_name AS Collation
    FROM sys.schemas s
    INNER JOIN sys.tables t ON t.schema_id = s.schema_id
    INNER JOIN sys.columns c ON c.object_id = t.object_id
    WHERE collation_name IS NOT NULL
    ORDER BY Column_Name;
        
  2. List All Supported Collations:

    You can use the following query to get a list of all supported collations:

    
    SELECT name, description FROM fn_helpcollations();
        
  3. List All Databases with Collation Names:

    This query lists all databases along with their collation names:

    
    SELECT name, collation_name FROM sys.databases;
        
  4. Find Server-Level Collation:

    To find the collation for the SQL Server instance, run the following query:

    
    SELECT @@servername AS server_name, 
           SERVERPROPERTY('Collation') AS Collation;
        
  5. Comparing Different Collation Strings:

    If you need to compare columns with different collation settings, you can use the COLLATE clause as shown here:

    
    SELECT *
    FROM TABLE1
    INNER JOIN TABLE2 
      ON TABLE1.Col1 COLLATE Latin1_General_CS_AS = 
         TABLE2.Col1 COLLATE Latin1_General_CS_AS;
        

These queries can help you manage and investigate collation settings, ensuring your database handles string data according to the desired rules for case sensitivity, accent sensitivity, kana sensitivity, and width sensitivity.

Server OS information

Finding Information About SQL Server Installation Using T-SQL

If you need to gather information about where SQL Server is installed, you can use the following T-SQL query. This script will provide details such as the server instance name, version, authentication mode, and more.


-- Declare a variable to get the SQL Server version
-- declare @version varchar(4)
-- select @version = substring(@@version,22,4)
-- select @@version
-- If SQL version is greater than or equal to 2012, continue

SELECT 
    SERVERPROPERTY('ServerName') AS [Instance Name],
    CASE LEFT(CONVERT(VARCHAR, SERVERPROPERTY('ProductVersion')), 4) 
        WHEN '11.0' THEN 'SQL Server 2012'
        WHEN '12.0' THEN 'SQL Server 2014'
        ELSE 'Newer than SQL Server 2014'
    END AS [Version Build],
    SERVERPROPERTY('Edition') AS [Edition],
    SERVERPROPERTY('ProductLevel') AS [Service Pack],
    CASE SERVERPROPERTY('IsIntegratedSecurityOnly') 
        WHEN 0 THEN 'SQL Server and Windows Authentication mode'
        WHEN 1 THEN 'Windows Authentication mode'
    END AS [Server Authentication],
    CASE SERVERPROPERTY('IsClustered') 
        WHEN 0 THEN 'False'
        WHEN 1 THEN 'True'
    END AS [Is Clustered?],
    SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [Current Node Name],
    SERVERPROPERTY('Collation') AS [SQL Collation],
    [cpu_count] AS [CPUs],
    [physical_memory_kb] / 1024 AS [RAM (MB)]
FROM 
    [sys].[dm_os_sys_info];

Example Output:


Version Build            Edition           Instance Name      Service Pack  Server Authentication  Is Clustered?  Current Node Name   SQL Collation                CPUs  RAM (MB)
Newer than SQL Server 2014  Express Edition (64-bit)  23-IT\SQLEXPRESS   RTM        SQL Server and Windows Authentication mode  False          23-IT           SQL_Latin1_General_CP1_CI_AS  8     8012

SQL Server Version Greater Than 2005

If your SQL Server version is greater than 2005, you can use the following script to find detailed system properties such as the version, edition, authentication mode, and server information.


SELECT 
    SERVERPROPERTY('ServerName') AS [Instance Name],
    CASE LEFT(CONVERT(VARCHAR, SERVERPROPERTY('ProductVersion')), 4) 
        WHEN '9.00' THEN 'SQL Server 2005'
        WHEN '10.0' THEN 'SQL Server 2008'
        WHEN '10.5' THEN 'SQL Server 2008 R2'
    END AS [Version Build],
    SERVERPROPERTY('Edition') AS [Edition],
    SERVERPROPERTY('ProductLevel') AS [Service Pack],
    CASE SERVERPROPERTY('IsIntegratedSecurityOnly') 
        WHEN 0 THEN 'SQL Server and Windows Authentication mode'
        WHEN 1 THEN 'Windows Authentication mode'
    END AS [Server Authentication],
    CASE SERVERPROPERTY('IsClustered') 
        WHEN 0 THEN 'False'
        WHEN 1 THEN 'True'
    END AS [Is Clustered?],
    SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [Current Node Name],
    SERVERPROPERTY('Collation') AS [SQL Collation],
    [cpu_count] AS [CPUs],
    [physical_memory_in_bytes] / 1048576 AS [RAM (MB)]
FROM 
    [sys].[dm_os_sys_info];

For further details on the SQL functions used in these queries, you can refer to the official Microsoft documentation:

Related Articles:

Popular Posts