Question

Just when I thought I was starting to understand SQL, I am completely lost with this. What is wrong with the syntax of the last SELECT?

if (OBJECT_ID('TestTable') IS NOT NULL) drop table TestTable

CREATE TABLE TestTable(
ID  Bigint IDENTITY(1,1) PRIMARY KEY,
Num1 bigint NOT NULL,
Num2 bigint NULL
)

INSERT INTO TestTable
VALUES (1,2)
SELECT 'TEXT', 'MORE TEXT', 'AND MORE TEXT'
SELECT 'TEXT', Num1 From TestTable
SELECT 'TEXT', Num1 From TestTable, 'MORE TEXT'
Was it helpful?

Solution

You have to list all the "columns" (quoted since they're not all actually columns in a table) you want selected before specifying their source.

The problem with:

SELECT 'TEXT', Num1 From TestTable, 'MORE TEXT'

is that you select two columns from TestTable then try to select another column. This is not standard SQL syntax. As per the documentation here (particularly the syntax diagram), the from clause is optional but, if there, it must follow the select list.

Once the parser encounters something not part of the select list, no more columns can be selected as part of the current query-specification. You can select more columns in another query-specification (in the query-expression) but that must be linked with the previous one with one of { UNION [ ALL ] | EXCEPT | INTERSECT }.

If you want those three columns in a single row, you should use:

SELECT 'TEXT', Num1, 'MORE TEXT' From TestTable

If you want an added row with MORE TEXT (I consider this very unlikely given it won't have enough columns for your output), you would have to use two query-specification sections linked with UNION ALL. Assuming you had a value you could use for the Num1 output column, you could use something like:

SELECT 'TEXT' as textcol, Num1 as numcol, From TestTable
UNION ALL
SELECT 'MORE TEXT' as textcol, 0 as numcol

OTHER TIPS

SELECT 'TEXT', Num1, 'MORE TEXT' From TestTable

or perhaps more usefull

SELECT 'TEXT' as col1, Num1 as col2, 'MORE TEXT' as col3 From TestTable

You have to finish your select column list before starting your from clause

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top