Mysterious variable in sql query - sql

I'm looking at some sql code with the following structure:
set #var =
(
select count(1) from
(
select * from table where field = 1
)
someVariable
)
It won't seem to run unless "someVariable" is in the statement. My question is, what does this "someVariable" represent, and why is it in the query? I don't understand why I can't set #var to the select count statement outright, so the "someVariable" is really throwing me off.

Derived tables need to have aliases. someVariable is functioning as an alias in this case.

When I run a similar query on MySQL, I got:
ERROR 1248 (42000): Every derived table must have its own alias
The inner select actually gives rise to a derived table, and someVariable is it's alias.

Related

Sub-Queries in Sybase SQL

We have an application which indexes data using user-written SQL statements. We place those statements within parenthesis so we can limit that query to a certain criteria. For example:
select * from (select F_Name from table_1)q where ID > 25
Though we have discovered that this format does not function using a Sybase database. Reporting a syntax error around the parenthesis. I've tried playing around on a test instance but haven't been able to find a way to achieve this result. I'm not directly involved in the development and my SQL knowledge is limited. I'm assuming the 'q' is to give the subresult an alias for the application to use.
Does Sybase have a specific syntax? If so, how could this query be adapted for it?
Thanks in advance.
Sybase ASE is case sensitive w.r.t. all identifiers and the query shall work:
as per #HannoBinder query :
select id from ... is not the same as select ID from... so make sure of the case.
Also make sure that the column ID is returned by the Q query in order to be used in where clause .
If the table and column names are in Upper case the following query shall work:
select * from (select F_NAME, ID from TABLE_1) Q where ID > 25

SQL Server query erroring with 'An object or column name is missing or empty'

I have the following query in a stored procedure in SQL server:
SELECT TLI.LESNumber
,COUNT(TLT.PL)
INTO #PWCM
FROM #tmpLESImport TLI
INNER JOIN tbl_LES L
on TLI.LESNumber=L.NUMB
WHERE ISNULL(L.DELT_FLAG,0)=0
AND L.SCHL_PK=#SCHL_PK
AND TLI.PL IS NOT NULL
AND LEN(TLI.PL)>0
GROUP BY LESNumber
HAVING COUNT(PL)>1
When the query is run I get the following error:
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
Can anyone tell me why? #PWCM does not appear anywhere until this query.
When you SELECT INTO a table, it creates the table (in this case, a temp table). In order to create a table, each column needs a name, which your count column does not. You just need to give it a name:
SELECT TLI.LESNumber,COUNT(TLT.PL) [NumRecords]
INTO #PWCM
FROM #tmpLESImport TLI
...
I had this error for this query
SELECT
CASE WHEN COALESCE([dbo].[my-table].[field],"") = '...' THEN 'A'
WHEN COALESCE([dbo].[my-table].[field],"") = '...' THEN 'B'
...
END AS aaa INTO ##TEMPTABLE
FROM [dbo].[my-table]
Turns out I had to change the "" inside the COALSCE into ''.
Solved it for me
I just came across this, and the core reason was actually related to an errant set of brackets in the code which made the engine think there was a missing alias. Something along the lines of:
select *
from SOME_TABLE
where x = 1
[]
A stringified version of the query included a parameter list for logging, but that was being issued as the query instead of the actual query object. Deleting [] at the end resolved it.

How to select result with empty set

I have sql query:
select * from table where id in (1,2)
1,2 are parameters which I add there dynamically. But what If I have empty set:
select * from table where id in ()
then this query call exception:
ERROR at line 1:
ORA-00936: missing expression
how should I create sql with empty set
You can always add null to your set, so when the real set is empty, you get no syntax error:
select * from table where id in (null,1,2)
vs
select * from table where id in (null)
Your generator would be simpler, too, because you can print a , in front of every item that you add, without checking if it's the first one or not.
Of course since you are generating your SQL, the standard precautions against SQL Injection apply: do not let user input anywhere near the SQL that you generate.
Try this
select * from table where id in (null)

SQL with LIMIT1 returns all records

I made a mistake and entered:
SELECT * FROM table LIMIT1
instead of
SELECT * FROM table LIMIT 1 (note the space between LIMIT and 1)
in the CLI of MySQL. I expected to receive some kind of parse error, but I was surprised, because the query returned all of the records in the table. My first thought was "stupid MySQL, I bet that this will return error in PostgreSQL", but PostgreSQL also returned all records. Then tested it with SQLite - with the same result.
After some digging, I realized that it doesn't matter what I enter after the table. As long as there are no WHERE/ORDER/GROUP clauses:
SELECT * FROM table SOMETHING -- works and returns all records in table
SELECT * FROM table WHERE true SOMETHING -- doesn't work - returns parse error
I guess that this is a standardized behavior, but I couldn't find any explanation why's that. Any ideas?
Your first query is equivalent to this query using a table alias:
SELECT * FROM yourtable AS LIMIT1
The AS keyword is optional. The table alias allows you to refer to columns of that table using the alias LIMIT1.foo rather than the original table name. It can be useful to use aliases if you wish to give tables a shorter or a more descriptive alias within a query. It is necessary to use aliases if you join a table to itself.
From the SQL lite documentation:
This is why I want DB engine to force the usage of keyword AS for alias names
http://beyondrelational.com/modules/2/blogs/70/posts/10814/should-alias-names-be-preceded-by-as.aspx
SELECT * FROM table LIMIT1;
LIMIT1 This has taken as alias by SQL, cause LIMIT1 is not a reserved literal of SQL.
Something after table name and that is not a reserved keyword always taken as an table alias by SQL.
SELECT * FROM table LIMIT 1;
When you used LIMIT just after the table name, SQL found that as a reserved keyword and worked for it as per the behavior. IF you want to use reserved key words in query It can be done by putting reserved literals in quotes. like..
SELECT * FROM table `LIMIT`;
OR
SELECT * FROM table `LIMIT 1`;
Now all words covered under `` quotes will treated as user defined.
Commonly we did mistake with date, timestamp, limit etc.. keywords by using them as column names.

T-SQL, Select #variable within a sub-query causes syntax error

I'm using a sub-query to get results needed (multiple records returned), and I want to put those results in a single record returned.
When I run the sub-query on its own, it works, but once I use it as a sub query, it no longer works due to a syntax error.
The following code causes a syntax error
(Incorrect syntax near '='.)
declare #test varchar(1000)
set #test = ''
SELECT description, (SELECT #test = #test + FirstName
FROM EMP_tblEmployee
)select #test
FROM EMP_tblCrew
So essentially, the sub query
(SELECT #test = #test + FirstName
FROM EMP_tblEmployee
)select #test
returns "charliejohnjacob"
The main query
SELECT description FROM EMP_tblCrew
returns "janitor"
So I want it to say
janitor | charliejohnjacob
2 fields, 1 record.
Your query is not syntactically correct and the T-SQL parser has a nasty habit of not reporting an error quite accurately at times. This is a bit of a stab in the dark but try:
SELECT
description,
(SELECT FirstName + ' ' FROM EMP_tblEmployee FOR XML PATH('')) AS [Name Concat Result]
FROM EMP_tblCrew
That will fix one thing at least, though I'm not sure how SQL server feels about concatenating inline like that. You also risk overflowing the varchar(1000) if your table is of appreciable size. Even varchar 8000 isn't very much for this kind of query.
Try searching google for "SQL Concatenate rows into string". There are a number of useful solutions for this.
It looks like you also need to join the employee to the crew table, so that you dont get some cartesian product (usually not what is wanted).
Probably the easiest path involves using a recursive CTE (common table expression). A detailed example of that is at https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
Note, this basically requires that you have sql 2008.
Another path would be to create a user defined function that returned the concatenated values from the EMP_tblEmployee table. You could do this in 2005 or 2008.