Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format SQLCMD output

I am using below command line to run a SQL query using SQLCMD

sqlcmd -S Server -Q "select top 100 * From people" -d people -t 10 

The table has 20 columns and when i look at output command line window wraps the text and makes it difficult to read.

I want my results to be displayed the same way it displays in SQL Server Management Studio (properly formatted). I am not looking for any grids, but i need all my columns to be displayed in row 1 and the results properly beneath.

Thanks in advance.

like image 901
user1550159 Avatar asked Nov 16 '15 15:11

user1550159


People also ask

How do you format SQL query?

Select Edit -> SQL Formatter -> Format Current Query (or press F12). Only the current query would be formatted. -- Format Selected Query: To format a selected query(s) in set of query(s), select the query(s) to be formatted. Select Edit -> SQL Formatter -> Format Selected Query (or press Ctrl+F12).

Can you format in SQL?

SQL Server FORMAT() FunctionThe FORMAT() function formats a value with the specified format (and an optional culture in SQL Server 2017). Use the FORMAT() function to format date/time values and number values. For general data type conversions, use CAST() or CONVERT().

How do I format a SQL Server database?

SQL Server supports two types of format files: XML formats and non-XML format files. Both non-XML format files and XML format files contain descriptions of every field in a data file, and XML format files also contain descriptions of the corresponding table columns.


2 Answers

Answer

We can set the width of each column.

C:/> sqlcmd -S my_server

> :setvar SQLCMDMAXVARTYPEWIDTH 30
> :setvar SQLCMDMAXFIXEDTYPEWIDTH 30
> SELECT * from my_table
> go

We can also set it like this: sqlcmd -S my_server -y 30 -Y 30.

Details

SQLCMDMAXVARTYPEWIDTH (-y)

It limits the number of characters that are returned for the large variable length data type

SQLCMDMAXFIXEDTYPEWIDTH (-Y)

Limits the number of characters that are returned for the following data types

Note: setting -y has serious performance implications.

See https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility

like image 67
Shaun Luttin Avatar answered Sep 19 '22 03:09

Shaun Luttin


Formatting issues usually pop up due to your console window. One solution is to output to the file and use notepad/your favorite editor:

sqlcmd -S myServer -d myDB -E -Q "select top 100 * From people" 
     -o "output.txt"
like image 30
Klark Avatar answered Sep 20 '22 03:09

Klark