Category: SQL Server

SQL Server Blog Archives, by Peter Whyte (Database Administrator).
Includes: Database Admin, Management Studio (SSMS), Windows Admin, PowerShell, WSL, MSSQL Backups, Restores & more…

  • Introducing DBASco: SQL Server Database Admin Blog

    Introducing DBASco: SQL Server Database Admin Blog

    Greetings Tech People!

    If you’ve been following my technical journey on peter-whyte.com, I’m excited to share a new platform that dives into the world of Database Reliability Engineering and beyond – welcome to DBASco.com!

    At DBASco.com, I share my latest technical writings, focusing on a spectrum of topics catering to IT enthusiasts, database/system administrators, and those passionate about the software behind reliability engineering. The primary categories align with the ones you’re familiar with at peter-whyte.com, ensuring a seamless transition for any dedicated readers.

    This site here is now my secondary tech blog site. If you’ve been on here before you will have seen a lot of display ads, which are disabled for the time being. I was using Ezioc, and I was earning around $50-60 per month, until I neglected things for too long during 2023 and there was a drop in earnings. The site certificate had issues during 2023 Q4, and we are back fully operational as of this week.

    My enjoyment is the technical writing, refining, and seeing where tests lead me, exploring my passion for the things I do as a career and on the side. I hope you enjoy what I write, and it serves a purpose if visiting via Online Search to understand a concept or resolve an issue.

    SSMS Logo

    DBASco Blog Categories

    DBASco: SQL Server: Explore Microsoft SQL Server with in-depth insights into queries, optimization techniques, and best practices. Uncover the holistic experience, including the realm of Windows Administration that intertwines seamlessly with the life of a SQL Server DBA.

    DBASco: PowerShell: Dive into the enchanting world of PowerShell scripting with hands-on guides, expert tips, and powerful tricks. Unearth the magic of automation as you streamline your workflow with carefully crafted scripts and comprehensive guides.

    DBASco: WSL and Linux: Journey into the world of Windows Subsystem for Linux (WSL) and Linux, discovering the synergy between these platforms and unraveling the potential for seamless integration. Benefit from real-world experiences and extensive testing, providing you with valuable insights into cross-OS platform development.

    DBASco: Other: From RDMS’s like MySQL, Postgres, Redshift to semi-related technologies like AWS, and even technical guides on WordPress and website management – expect a wealth of knowledge that keeps you at the forefront of the ever-evolving tech landscape.

    SSMS Logo

    DBASco Latest Articles

    RedShift: Script to Show Running Queries
    Published on January 24, 2024
    Uncover the power of Amazon Redshift, a cloud-based data warehousing giant. Learn how to efficiently manage and analyze extensive datasets with a detailed script to reveal running queries.

    RedShift: Creating a User and Promoting to Superuser
    Published on January 24, 2024
    Unlock the secrets of Amazon RedShift as we guide you through creating a user and elevating their privileges to superuser status. Essential insights for effective cluster management.

    PowerShell Script: List Files with Sizes and Dates
    Published on January 23, 2024
    Master a practical PowerShell script that simplifies listing files in a directory. Dive into efficient file management with sizes and dates at your fingertips.

    Backing Up a Database in SQL Server Using Command
    Published on January 22, 2024
    Ensure the safety and integrity of your data with a comprehensive guide on backing up a database in SQL Server using command-line tools. A crucial aspect of database management unveiled.

    SQL Server Script: Get Last Backup Dates
    Published on January 22, 2024
    Stay informed about the last backup times, a critical element in maintaining data integrity. Enhance your SQL Server skills with a script that simplifies tracking backup dates.

    PowerShell: Counting Files, Words and Rows
    Published on January 22, 2024
    Embark on a PowerShell journey with a script that counts files, words, and rows. Discover the power of PowerShell for efficient data processing and analysis.

    Adding a Filegroup in SQL Server
    Published on January 21, 2024
    Learn the process of adding a new filegroup to a database in SQL Server. Elevate your database architecture skills with a step-by-step guide.

  • Temp Tables in SQL Server

    Temp Tables in SQL Server

    Temp tables in SQL Server can improve the efficiency and performance of complex queries by breaking them down into smaller pieces, storing intermediate results in memory, and eliminating unnecessary data.

    In SQL Server, temporary tables are tables that are created for a specific purpose and are only available for the duration of the connection that created them. They can be created using either the # symbol or the ## symbol, with each symbol having slightly different behaviours.

    Local Temp Tables
    Temp tables created using the “#” symbol are known as local temp tables. These tables are only available to the connection that created them, and they are automatically dropped when the connection is closed. Local temp tables are commonly used and useful when you need to store and manipulate intermediate results within a query or stored procedure.

    Global Temp Tables
    These tables are available to any connection, and they are not automatically dropped when the connection that created them is closed. Global temp tables are useful when you need to share data between different connections or when you want to store data that needs to persist beyond the lifetime of a single connection or session.

    Below I’ll demo how to perform the following on Temp Tables in SQL Server:
    Create a Local Temp Table
    Insert Rows into Temp Table
    Create an Index on Temp Table
    Select From Temp Table
    Drop Temp Table

    Create a Local Temp Table

    This statement creates a temporary table called #Chicken in a local scope:

    -- Create a local temp table called #Chicken
    CREATE TABLE #Chicken (
       ID INT,
       Name VARCHAR(50),
       Type VARCHAR(50),
       Price DECIMAL(18,2)
    );
    

    This temp table will be short-lived as it exists only for the duration of my current SSMS session. It is only accessible from the session in which it was created and is automatically dropped when the session ends (when I close the query window or it disconnects).

    Insert Rows into Temp Table

    This statement inserts four rows of data into the temporary table #Chicken:

    -- Insert four rows of data into the #Chicken table
    INSERT INTO #Chicken (ID, Name, Type, Price)
    VALUES (1, 'Roasted Chicken', 'Whole', 14.99),
           (2, 'Fried Chicken', 'Wings', 9.99),
           (3, 'Grilled Chicken', 'Breast', 12.99),
           (4, 'Teriyaki Chicken', 'Stir Fry', 11.99);
    

    Create an Index on Temp Table

    In this next statement, I’m creating an index on the #Chicken temporary table to improve query performance:

    -- Create an index on the Type column to improve query performance
    CREATE INDEX idx_chicken_type ON #Chicken (Type);
    

    An index in MSSQL is a data structure that allows faster search and retrieval of data from a table. By creating an index on the Type column of the #Chicken table, the database engine can more efficiently locate and retrieve rows based on the values in that column.

    Select From Temp Table

    This statement retrieves all rows from the temporary table #Chicken:

    -- Retrieve all rows from the #Chicken table
    SELECT * FROM #Chicken;
    
    Create Temp Table SQL Server

    Drop Temp Table

    This statement drops a temporary table called #Chicken.

    -- Drop local temp table (also happens on session disconnect)
    DROP TABLE #Chicken;
    

    When a temporary table is no longer needed, it can be removed using the DROP TABLE statement. Dropping a temporary table removes it from the database and frees up the space it occupied.

    We should give global temp tables more attention for this clean-up part. Global temp tables are visible to all connections which means they are not automatically dropped. It is important to drop global temp tables when they are no longer needed to prevent clutter and ensure efficient use of resources.

  • Move Temp DB SQL Server

    Move Temp DB SQL Server

    A common best practice for SQL Server DBA’s is to have Temp DB files stored on a separate drive, especially ensuring that it’s not on the C:\ drive and sharing with the OS.

    This is because Temp DB can grow very large, very quickly. The growth of Temp DB Files depends on the workload/queries happening on your SQL Server. Temp DB growth can happen on both the data and log files.

    This post is a tutorial on how to move all Temp DB files from one volume to another in SQL Server.

    Downtime is required for this action, so we should ensure we have a planned maintenance window for this work.

    Move Temp DB Files MSSQL

    First, I’m going to use sp_helpfile to view logical Temp DB names.

    -- move temp db files sql server
    USE temp db;
    GO
    
    -- check physical names and attributes for current database
    exec sp_helpfile;
    
    sp_helpfile sql

    We can see this SQL Server Instance has 8x temp_db data files and one temp_db log file.

    Next, run the following script to generate the ALTER statements required to move these files. You’ll need to amend the FILENAME parameter to the new location.

    Temp DB SQL Server

    Grab the SQL output from here and then run the ALTER DATABASE commands.

    -- move temp_DB database to new location on disk
    -- (amend temp_db to actual db name)
    ALTER DATABASE temp_db MODIFY FILE (NAME = [tempdev], FILENAME = 'D:\mssql_temp_db\tempdev.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [templog], FILENAME = 'D:\mssql_temp_db\templog.ldf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp2], FILENAME = 'D:\mssql_temp_db\temp2.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp3], FILENAME = 'D:\mssql_temp_db\temp3.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp4], FILENAME = 'D:\mssql_temp_db\temp4.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp5], FILENAME = 'D:\mssql_temp_db\temp5.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp6], FILENAME = 'D:\mssql_temp_db\temp6.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp7], FILENAME = 'D:\mssql_temp_db\temp7.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp8], FILENAME = 'D:\mssql_temp_db\temp8.mdf');
    
    alter database sql server

    The file “tempdev” has been modified in the system catalog. The new path will be used the next time the database is started.

    The above output message informs that we have to restart the SQL Service for this change to take effect. So let’s do that now.

    Restart MS SQL Service

    Once done, we can check the active temp db files in our new directory.

    Temp Database SQL Files

    And verify in MSSQL by using exec sp_helpfile as above in this demo, or by opening the database Shrink File window in SSMS.

    MSSQL Temp Database Files

    Lastly, remember to delete the old Temp DB files from where you moved them from.

    I hope this guide provided you with some insight and that your change goes without issues! Feel free to check out my Database Admin tips tag for more random posts from a SQL DBA.

  • SSMS

    SSMS

    SSMS, SQL Server Management Studio, is the standard application that we use to run queries and administer instances of SQL Server.

    The Microsoft Documentation and links to download can be found here – Download SSMS

    My blog posts with the SQL Server Management Studio (SSMS) Tag may help guide you through common configuration tasks and/or resolve issues when using SSMS.

    SSMS Maximum Characters Displayed, September 12, 2022
    SSMS Show Line Numbers, September 3, 2022
    How to Connect to SQL Server with Windows Authentication using a Different Domain, August 25, 2022
    USE Command in SQL Server, November 25, 2020
    Change Default Database in SQL Server, November 23, 2020
    Disk Usage by Top Tables Report in SQL Server, October 4, 2020
    Include Execution Trace Messages in SQL Server Error Logs, May 5, 2020
    “Index was out of range” SQL Server Management Studio, April 15, 2019
    The (SSMS) Import Flat File Feature, January 24, 2019
    Using Custom Connection Colours in SSMS, October 22, 2018
    Exporting SQL Server Query Results to CSV, October 2, 2018

    Hope this is useful for you. This page will be updated as I publish more blog posts in this area.

  • How to Check SQL Server Version

    How to Check SQL Server Version

    Checking your SQL Server versions is a common task, as most database administrators will know how important it is to keep the software on the host up to date. This post is here to help you to check the version of SQL Server instances.

    You may have many instances running on the same host server all running on different versions. To check if you have more than one MS SQL Instance, open SQL Server Configuration Manager or Services.msc on your host. If it’s a multi-tenant MSSQL host there will be more than one SQL Server Service and the same for other SQL Services like the SQL Agent Service.

    As ever, there are many ways to get such metadata information from SQL Server. Here are a few example ways to check your SQL Server version:
    # TSQL – SELECT @@VERSION / SERVERPROPERTY
    # SSMS GUI – SQL Server Options

    When you have your SQL Server versions noted, you’ll then want to check how up-to-date you are. There are base SQL Server Build numbers (16.0..) and then minor version numbers (0.700.4). You can learn more about determining the version of your SQL Server with the help of Microsoft Docs.

    SQL Query – SELECT @@VERSION / SERVERPROPERTY

    One of the quickest ways to get the SQL Server version is to use the @@VERSION in-built TSQL function, as shown in the example below.

    -- Get Running MSSQL Version
    SELECT @@VERSION;
    check sql server version

    Running this will show your MS SQL Major version number, Microsoft SQL Server 2022 (CTP2.1) in this case. It also shows the build version number, 16.0.700.4, which I can cross-check with this sqlserverbuilds website to verify I’m running the latest SQL Server version available. Also, note the Microsoft Docs link provided at the top of this post.

    We can also get this SQL Server version information using another built-in Function, and I’m including other examples for system metadata collection for diagnostics.

    -- TSQL Functions for Other Metadata
    SELECT 
    	@@SERVERNAME AS 'hostname',
    	@@SERVICENAME AS 'instance',
    	@@SPID AS 'current_running_SPID_ID',
    	@@VERSION AS 'mssql_version',
    	CASE
            WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('productversion')) LIKE '10.0%' THEN 'SQL2008'
            WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('productversion')) LIKE '10.5%' THEN 'SQL2008 R2'
            WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('productversion')) LIKE '11%' THEN 'SQL2012'
            WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('productversion')) LIKE '12%' THEN 'SQL2014'
            WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('productversion')) LIKE '13%' THEN 'SQL2016'
            WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('productversion')) LIKE '14%' THEN 'SQL2017'
            WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('productversion')) LIKE '15%' THEN 'SQL2019'
            WHEN CONVERT(VARCHAR(128), SERVERPROPERTY('productversion')) LIKE '16%' THEN 'SQL2022'
    		ELSE 'unknown'
    	END AS 'mssql_version_short';
    MS SQL SERVERPROPERTY

    SSMS GUI – SQL Server Options

    The other way to get your SQL Server Version information is to do it in SQL Server Management Studio (SSMS).

    In SSMS Object Explorer, right-click the server at the top then select Properties, as shown in the example below.

    SSMS SQL Server Properties

    This will open up the SQL Server Properties window where we are able to see the MS SQL version.

    SQL Version

    I hope this guide has given you the information you need to check SQL Server build numbers and MS SQL versions. Feel free to check out my SQL Tips tag for more random MSSQL tips from a SQL DBA.

  • SSMS Silent Install

    SSMS Silent Install

    This is a note on how to silently install SQL Server Management Studio (SSMS) via command (PowerShell).

    SSMS is a tool most people use to administer SQL Server and to run SQL queries. If you need to install SSMS many times or on multiple computers, you may want to use the silent installation feature when automating the process.

    This ‘silent‘ installation allows you to install SSMS without any user interaction, making it quick and easy to deploy on multiple computers. In this demo, we are using the Standard Microsoft Installer Command-Line Quiet Option (/q).

    How to Silently Install SSMS

    To perform a silent installation of SSMS, you will need a copy of the SSMS installation files.
    You can download SSMS from this link here: SSMS Download (Microsoft Docs)

    Open Windows Terminal or any command prompt for PowerShell as Administrator and navigate to the directory where you have the SSMS installation files downloaded. Then run the msi exec command as shown:

    # Navigate to directory with ssms download
    cd ssms
    gci
    
    # Install SSMS (silently)
    .\SSMS-Setup-ENU.exe /q
    SSMS Silent Install

    The only parameter being used here is /q which specifies that the installation should be performed silently. So SSMS will install in the background and your terminal prompt will return to a command-ready state when the installation has been completed.

    SSMS will be installed silently on the host and be ready for use. That should be all there is to this one. Feel free to check out the SSMS Tips Tag for more useful information about this application.

  • SSMS Maximum Characters Displayed

    SSMS Maximum Characters Displayed

    By default, the max number of characters displayed in a single column of a query in SSMS when outputting as text is 256 characters.

    We can amend our query outputs in SSMS to Results to Text, rather than the default grid layout. This can be done by clicking the top bar menu button as shown in the screenshot below.

    SSMS Results to Text Option

    If using text output rather than grid, you may encounter issues with truncated query outputs if a column contains more than 256 chars.

    The screenshot below shows an example of a truncated column, only showing 256 out of 550 characters in the column.

    SSMS Maximum Characters Results to Text

    The demo below shows how to fix this and increase this SSMS default value to the maximum chars allowed.

    Increase SSMS Maximum Characters for Results To Text

    To increase your SSMS Maximum Characters for Results to Text, follow these steps.

    1. Click Tools at the top menu bar and select Options.

    SSMS Open Options Menu

    2. Navigate to Query Results > SQL Server > Results to Text.

    SSMS Results to Text Max Chars

    3. Open a new query Window and re-run your query or procedure.

    SSMS Results to Text Full

    That’s it, working for you now… I hope.

    The reason I note this one down as a blog post is that there are rare occasions where you might need to use Results to Text as a DBA. One example, when working with MSSQL Replication, the output of sp_scriptdynamicupdproc will likely contain more than 256 characters for the procedure statement output.

    Feel free to check out my SSMS Tips tag for more random Management Studio tips and stuff.

  • Add Columns to a Table in SQL Server

    Add Columns to a Table in SQL Server

    Adding new columns to tables in SQL Server is a common task for anyone developing and/or maintaining databases, usually driven by the need for new features on an application/script procedure.

    As ever, before you get started with MSSQL changes, have a look at the relevant Microsoft Documentation – Add Columns to a Table

    If the SQL Server instance has Replication configured have a look at MS Docs: Considerations for Schema Changes & Replicate Schema Changes
    By default, if we add a column it will be propagated through to Subscribers. If you are adding default values you should be mindful of Replication Latency.

    The following is included in this post:
    # Add Column to Table
    # Add Column to Table with Default Value

    Add Column to Table MSSQL

    Adding a column to a table is done using the ALTER TABLE statement. Here is an example of adding a column with the VARCHAR Data Type. The new column must allow NULL values or include a default constraint.

    -- Add column to table ms sql
    ALTER TABLE sqlBlog ADD tag VARCHAR(60);
    SQL Server Add Column

    We can run a quick SELECT TOP 1 * on the table to verify the new column exists. If this table contains sensitive data then we can also query sys.columns.

    Add Column to Table with Default Value

    As mentioned above in this post, if the SQL Server instance has Replication configured we should refer to Microsoft Docs prior to making this change. If you are adding columns with default values, you should also be mindful of Replication Latency and Transaction Log file sizes.

    The following shows adding a column with the default INT value of ‘12345’. Before doing this I inserted some more rows into the demo table.

    -- Add column to table with default value
    -- CONSTRAINT = Optional constraint name
    ALTER TABLE sqlBlog ADD epmv INT CONSTRAINT epmv_def DEFAULT 12345 WITH VALUES;
    Add Column to Table with Default Value

    Each existing row has had this ‘epmv’ value added as displayed above.

  • SSMS Show Line Numbers

    SSMS Show Line Numbers

    This post contains a guide on how to show line numbers in the SSMS query window. Useful if you want to see line numbers while you code.

    As well as general preference, enabling line numbers in SQL Server Management Studio is particularly useful when debugging an error message in a SQL script.

    The demo below includes the following:
    # Show Line Numbers in SSMS
    # Debugging Example

    Show Line Numbers in SSMS

    To enable line numbers in Management Studio, click Tools at the top menu bar and select Options.

    SSMS Tools Options

    Navigate to Text Editor > Transact-SQL > General and tick Line Numbers.

    SSMS Show Line Numbers

    Click OK, and you’ll see now see line numbers in the SSMS query window.

    SSMS Line Numbers

    Debugging Example

    When you are debugging a SQL script within SSMS, showing line numbers might help you when encountering an error like this one below.

    I’ve opened a random Stored Procedure, amended and attempted to run it, knowing it will fail.

    SQL Error Line

    The line our code has failed on is included in the output error message:
    Msg 102, Level 15, State 1, Procedure sp_addlogin, Line 33 [Batch Start Line 7]
    Incorrect syntax near ‘gif’.
    Msg 156, Level 15, State 1, Procedure sp_addlogin, Line 35 [Batch Start Line 7]
    Incorrect syntax near the keyword ‘else’.

    Line numbers shown in these error messages aren’t always accurate, but it should give you a pointer to the section of broken code.

    You can Double-Click the error message to bring you to the referenced line number, or use the Go To Line feature (CTRL + G).

  • Add a Filegroup to a Database in SQL Server

    Add a Filegroup to a Database in SQL Server

    This post contains a demo on how to add a new Filegroup for a database in SQL Server. Most databases work well with single data/log files and do not need this.

    Database files in SQL Server generally operate with 2 files, data (.mdf) files and log (.ldf) files. If we add an additional data file, we call it a user-defined (.ndf) data file. Filegroups are a grouping of these user-defined data files.

    Database Administrators may add new data files with the aim to improve the performance of a database or several databases on an instance, splitting the data files and data onto more than one disk drive. Another reason you might be adding a new data file in SQL Server is when you are configuring Change Data Capture (CDC), it’s a best practice to create a separate Filegroup for the CDC data.

    Filegroups in SQL Server are a grouping of user-defined data files. The demo below includes creating a new Filegroup with 2x data files. For more information and descriptions on Filegroups, see Microsoft Docs: Filegroups & MS SQL Database File Recommendations

    Add New Filegroup for a Database

    The SQL below will create a Filegroup and add 2x new files for storing the data. More info on syntax – Microsoft Docs: ALTER DATABASE File and Filegroup Options

    We are creating a demo database and adding a Filegroup here:

    -- Create a test database
    CREATE DATABASE [sqlDBA];
    
    USE [sqlDBA];
    GO
    -- Create test tables & insert rows from system tables
    SELECT * INTO dbo.raw_sysdatabases FROM sys.databases;
    SELECT * INTO dbo.raw_sysobjects FROM sys.system_objects;
    
    -- Create a filegroup
    ALTER DATABASE [sqlDBA] ADD FILEGROUP [sqlDBA_FG1];
    -- Check filegroups for current database
    SELECT * FROM sys.filegroups;
    SQL Server Add Filegroup

    Now we add the new data file(s) to the Filegroup in the sqlDBA database:

    -- Create data files for Filegroup
    ALTER DATABASE [sqlDBA]
    ADD FILE
    (
        NAME = sqldba_data1,
        FILENAME = 'D:\mssql_data\sqldba_data1.ndf',
        SIZE = 500MB,
        FILEGROWTH = 50MB
    ),
    (
        NAME = sqldba_data2,
        FILENAME = 'D:\mssql_data\sqldba_data2.ndf',
        SIZE = 500MB,
        FILEGROWTH = 50MB
    ) TO FILEGROUP [SQLDBA_FG1];
    
    -- Check files for a database
    USE [sqlDBA];
    GO
    SELECT 
    	file_id, type, type_desc, data_space_id, name, 
    	physical_name, state, size, max_size, is_percent_growth, growth
    FROM sys.database_files;
    SQL Server Add Database File

    To check database files via GUI, go to the Shrink Databases option in SQL Server Management Studio.

    SSMS > Right-Click Database > Tasks > Shrink:

    SQL Server Shrink Databases

    If you’re wondering what kind of data would be useful to have in a database filegroup, here’s an example from my other recent blog post where we create a filegroup for CDC data – How to Enable Change Data Capture (CDC) in SQL Server