简体   繁体   中英

Formatting the output using select statement

I have two select statements which are as mentioned below

SELECT 'MY OUTPUT'
SELECT * FROM MY TABLE

On execution MY OUTPUT is printed first and then there is a gap for next select.

I want to use something like UNION to combine two statements.

I'm using:

SELECT 'MY OUTPUT' UNION
SELECT * FROM MY TABLE

But, I am getting error:

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

SELECT 'MY OUTPUT' # this query return one column
UNION 
SELECT * FROM MY TABLE # this query return more than one column

number of columns must be the same

SELECT 'MY OUTPUT' UNION # return one column
SELECT column1 FROM MY TABLE # return one column now it will work

but i think you want to do this no?

SELECT 'MY OUTPUT',column1,Column2,column3 FROM MY TABLE

So here's what's happening:

The error you're getting (All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.) is because there are more columns in one select than the other.

You could use the same blank columns in your first query as there are in [My Table] which would make your query look like:

SELECT 'MY OUTPUT' , '', '' ,'', '' --(no. of columns should match those in MY TABLE)
UNION
SELECT * FROM [MY TABLE]

I'm guessing you want an excel style cell merge which is not possible as the output of a select query unfortunately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM