Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

Format column length in SSMS output

Asked by Ankur Vaish Apr 16, 2021 2.7K views 2 answers
Share

About this question

SQL Server 2012. Sample query at the bottom of this post. I'm trying to create a simple report for when a given database was last backed up. When executing the sample query with output to text in SSMS, the DB_NAME column is formatted to be the max possible size for data (the same issue exists in DB2, btw). So, I've got a column that contains data that is never more than, say, 12 characters, but it's stored in varchar(128), I get 128 characters of data no matter what. RTRIM has no effect on the output. Is there an elegant way that you know of to make the formatted column length be the max size of actual data there, rather than the max potential size of data? I guess there exists an xp_sprintf() function, but I'm not familiar with it, and it doesn't look terribly robust. I've tried casting it like this:

DECLARE @Servername_Length int; SELECT @Servername_Length = LEN( CAST( SERVERPROPERTY('Servername') AS VARCHAR(MAX) ) ) ; ... SELECT CONVERT(CHAR(@Servername_Length), SERVERPROPERTY('Servername')) AS Server, ...

But then SQL Server won't let me use the variable @database_name_Length in my varchar definition when casting. SQL Server, apparently, demands a literal number when declaring the char or varchar variable.

I'm down to building the statement in a string and using something like sp_executesql, or building a temp table with the actual column lengths I need, both of which are really a bit more trouble than I was hoping to go to just to NOT get 100 spaces in my output on a 128 character column. Have searched the interwebs and found bupkus. Maybe I'm searching for the wrong thing, or Google is cross with me.

It seems that SSMS will format the column to be the maximum size allowed, even if the actual data is much smaller. I was hoping for an elegant way to "fix" this without jumping through hoops. I'm using SSMS 2012. If I go to Results To Grid and then to Excel or something similar, the trailing space is eliminated. I was hoping to basically create a report that I email, though.


Sample query

-------------------------------------------------------------------------- QUERY: -------------------------------------------------------------------------- SELECT CONVERT(CHAR(32), SERVERPROPERTY('Servername')) AS Server, '''' + msdb.dbo.backupset.database_name + '''', MAX(msdb.dbo.backupset.backup_finish_date) AS last_db_backup_date FROM msdb.dbo.backupmediafamily INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id WHERE msdb..backupset.type = 'D' GROUP BY msdb.dbo.backupset.database_name ORDER BY msdb.dbo.backupset.database_name


Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Jul 5, 2024

To format column lengths in SQL Server Management Studio (SSMS) output, you can use several techniques depending on the specific requirements and the type of output you are working with. Here are a few common approaches:

1. Using FORMAT Function

The FORMAT function allows you to format the appearance of date, number, and currency data in your query results.

SELECT 
    FORMAT(someNumberColumn, 'N2') AS FormattedNumber, -- Format number with 2 decimal places
    FORMAT(someDateColumn, 'yyyy-MM-dd') AS FormattedDate -- Format date as YYYY-MM-DD
FROM 
    YourTable;

Example:

2. Using CAST and CONVERT

You can also use CAST and CONVERT functions to change the data type and format the output accordingly.

Example:

  SELECT     CAST(someNumberColumn AS DECIMAL(10,2)) AS FormattedNumber,    CONVERT(VARCHAR(10), someDateColumn, 120) AS FormattedDate -- Format date as YYYY-MM-DDFROM     YourTable;3. Using LEFT, RIGHT, and SUBSTRING

For text columns, you might want to limit the length of the output using LEFT, RIGHT, and SUBSTRING functions.

Example:

  SELECT     LEFT(someTextColumn, 10) AS ShortText -- Limit text to 10 charactersFROM     YourTable;

4. Setting Column Width in SSMS Results to Text

If you are exporting results or want to control column width in the "Results to Text" mode in SSMS, you can adjust the settings.

  Go to Tools > Options.

In the Options dialog, expand Query Results > SQL Server > Results to Text.

Set the Maximum number of characters displayed in each column to your desired value.

5. Using FORMATMESSAGE for Custom Formatting

FORMATMESSAGE can be useful for custom formatting strings.

Example:

  SELECT     FORMATMESSAGE('%-10s', someTextColumn) AS PaddedText -- Pad text to 10 characters widthFROM     YourTable;

6. Using Space Padding for Fixed Column Width

You can manually pad strings with spaces to achieve a fixed column width.

Example:

  SELECT     LEFT(someTextColumn + REPLICATE(' ', 10), 10) AS FixedWidthTextFROM     YourTable;

Example Query Combining Techniques

Here’s a comprehensive example combining several formatting techniques:

  SELECT     FORMAT(someNumberColumn, 'N2') AS FormattedNumber,    FORMAT(someDateColumn, 'yyyy-MM-dd') AS FormattedDate,    LEFT(someTextColumn, 10) AS ShortText,    FORMATMESSAGE('%-20s', someOtherTextColumn) AS PaddedText,    LEFT(someTextColumn + REPLICATE(' ', 10), 10) AS FixedWidthTextFROM     YourTable;

This query formats numeric and date columns, shortens a text column to a fixed length, pads another text column to a fixed width, and combines several methods to achieve well-formatted output.

Conclusion

By using functions like FORMAT, CAST, CONVERT, and FORMATMESSAGE, along with SSMS settings, you can control the format and appearance of your query results to suit your needs. Adjusting these techniques will help you achieve the desired output formatting in SSMS.









Was this helpful?

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.