Hi,
input file is with simple command like "Select top 10 * from Test"
First of all to must understand that you should NOT use such queries! You should explicitly use the name of the columns in your query. In fact, this is related to the solution indirectly.
Yellow marked line need to be remove from o/p
This requirement is actually not so rare and there is a very simple solution, but not the one I will recommend :-)
Solution
All you need to do is to SELECT the name of the columns (hard coded) and UNINON ALL
with your query, while CONVERT the values into VARCHAR. You use the -h
parameter with value -1
to hide the headers and the unwanted line separator (the headers will come from your first query in the UNION) and use SET NOCOUNT ON
to hide the number of rows effected.
The reason this is not recommended is the need to convert all values to string (VARCHAR for example). You need to remember that for performance this is not a good idea since we CONVERT an efficient data type (like bit
or tiniint
into to a data type that requires a lot more data length (need to pass more data in the network) like NVARCHAR and it is less efficient for processing.
For small amount of data this is not critical.
For example
If we have the query: SELECT C1,C2,C3 FROM TBL
then we can execute instead the query
SELECT 'C1','C2','C3'
UNION ALL
SELECT
CONVERT(NVARCHAR(10),C1),
CONVERT(NVARCHAR(10),C2),
CONVERT(NVARCHAR(10),C3)
FROM TBL
This will produce the requested result
Note! In most cases it is much better to use PowerShell using the comment Invoke-Sqlcmd
, as I wrote in my first response
Note! if all you need is to get the result of the query in file and this does not have to be done using scripts, then you can use the SSMS and simply select to return the result in text file instead of a grid