0

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.

2
  • SQL stands for "Structurized Query Language" and is designed to make queries to a database and output a machine-understandable output. It is NOT designed for nice formatting. Commented Jul 19, 2016 at 2:20
  • How many columns does your table have, and can you list them here? Commented Jul 19, 2016 at 2:24

2 Answers 2

1
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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.