Derby SELECT statement failing to find a specific string - sql

I have a table that contains a column called ATEST, in a schema called TESTSCHEMA, that is in a database called SESSION.
I am trying to find records whose ATEST column has a string called "MyTest".
I am using the following SQL:
final String query = "SELECT * FROM SESSIONDATA.SESSIONS WHERE SESSION.TESTSCHEMA.ATEST = 'MyTest'";
Now I have placed several records whose ATEST column contains "MyTest". I use JDBC in the usual way:
device = aConnect.prepareCall(query);
ResultSet result = device.executeQuery();
Note that, for brevity, try and catch code is being omitted since I am not getting any exceptions thrown.
For some reason, I keep getting what amounts to empty result sets. I cannot get this statement to find any records despite the fact that I have several records in the database where ATEST = 'MyTest'!
Have I found a bug in Derby? Searches without WHERE clauses or where WHERE clauses look for numbers seem to work without problems. Why doesn't a WHERE clause that looks for a string find the strings, despite the fct that the strings are actually in the database???
Someone please advise.

Try sending like
final String query = "SELECT * FROM SESSIONDATA.SESSIONS WHERE SESSION.TESTSCHEMA.ATEST = '''MyTest'''";
It should hit DB like
SELECT * FROM SESSIONDATA.SESSIONS WHERE SESSION.TESTSCHEMA.ATEST = 'MyTest'
instead of
SELECT * FROM SESSIONDATA.SESSIONS WHERE SESSION.TESTSCHEMA.ATEST =MyTest

I don't know Derby. But your query looks strange:
You say the database is called SESSION. So this is where you connect to. I wouldn't expect it's name in a query.
Your schema is called TESTSCHEMA. So this is where the tables reside in. ATEST is a column. So aren't you missing the table name between schema and column in TESTSCHEMA.ATEST?
You select from SESSIONDATA.SESSIONS. What is SESSIONDATA suddenly? It's neither of the names you mentioned. What is SESSIONS? Is that the table name?
I would expect a query about like this:
SELECT * FROM testschema.sessions WHERE atest = 'MyTest'
(Where the schema name might even be superfluous in case it's the default schema for your connection.)

Try using a numeric value for referencing in place of 'Mytest'
Replace
SELECT * FROM SESSIONDATA.SESSIONS WHERE SESSION.TESTSCHEMA.ATEST = 'MyTest'
with
SELECT * FROM SESSIONDATA.SESSIONS WHERE SESSION.TESTSCHEMA.ATEST = 123

Related

Can I use a query parameter in a table name?

I want to do something along the lines of:
SELECT some_things
FROM `myproject.mydataset.mytable_#suffix`
But this doesn't work because the parameter isn't expanded inside the table name.
This does work, using wildcard tables:
SELECT some_things
FROM `myproject.mydataset.mytable_*`
WHERE _TABLE_SUFFIX = #suffix
However, it has some problems:
If I mistype the parameter, this query silently returns zero rows, rather than yelling at me loudly.
Query caching stops working when querying with a wildcard.
If other tables exist with the mytable_ prefix, they must have the same schema, even if they don't match the suffix. Otherwise, weird stuff happens. It seems like BigQuery either computes the union of all columns, or takes the schema of an arbitrary table; it's not documented and I didn't look at it in detail.
Is there a better way to query a single table whose name depends on a query parameter?
Yes, you can, here's a working example:
DECLARE tablename STRING;
DECLARE tableQuery STRING;
##get list of tables
CREATE TEMP TABLE tableNames as select table_name from nomo_nausea.INFORMATION_SCHEMA.TABLES where table_name not in ('_sdc_primary_keys', '_sdc_rejected', 'fba_all_order_report_data');
WHILE (select count(*) from tableNames) >= 1 DO
SET tablename = (select table_name from tableNames LIMIT 1);
##build dataset + table name
SET tableQuery = CONCAT('nomo_nausea.' , tablename);
##use concat to build string and execute
EXECUTE IMMEDIATE CONCAT('SELECT * from `', tableQuery, '` where _sdc_deleted_at is not null');
DELETE FROM tableNames where table_name = tablename;
END WHILE;
In order to answer your stated problems:
Table scanning happens in FROM clause, in WHERE clause happens filtering [1] thus if WHERE condition is not match an empty result would be returned.
"Currently, Cached results are not supported when querying with wildcard" [2].
"BigQuery uses the schema for the most recently created table that matches the wildcard as the schema" [3]. What kind of weird stuff you have faced in your use case? "A wildcard table represents a union of all the tables that match the wildcard expression" [4].
In BigQuery parameterized queries can be run, But table names can not be parameterized [5]. Your wildcard solution seems to be the only way.
You can actually use tables as parameters if you use the Python API, but it's not documented yet. If you pass the tables as parameters through a formatted text string vs. a docstring, your query should work.
SQL example:
sql = "SELECT max(_last_updt) FROM `{0}.{1}.{2}` WHERE _last_updt >= TIMESTAMP(" +
"CURRENT_DATE('-06:00'))".format(project_id, dataset_name, table_name)
SQL in context of Python API:
bigquery_client = bigquery.Client() #setup the client
query_job = bigquery_client.query(sql) #run the query
results = query_job.result() # waits for job to complete
for row in results:
print row

Inserting new rows into table-1 based on constraints defined on table-2 and table-3

I want to append new rows to a table-1 d:\dl based on the equality constraint lower(rdl.subdir) = lower(tr.n1), where rdl and tr would be prospective aliases for f:\rdl and f:\tr tables respectively.
I get a function name is missing ). message when running the following command in VFP9:
INSERT INTO d:\dl SELECT * FROM f:\rdl WHERE (select LOWER(subdir)FROM f:\rdl in (select LOWER(n1) FROM f:\tr))
I am using the in syntax, instead of the alias based equality statement lower(rdl.subdir) = lower(tr.n1) because I do not know where to define aliases within this command.
In general, the best way to get something like this working is to first make the query work and give you the results you want, and then use it in INSERT.
In general, in SQL commands you assign aliases by putting them after the table name, with or without the keyword AS. In this case, you don't need aliases because the ones you want are the same as the table names and that's the default.
If what you're showing is your exact code and you're running it in VFP, the first problem is that you're missing the continuation character between lines.
You're definitely doing too much work, too. Try this:
INSERT INTO d:\dl ;
SELECT * ;
FROM f:\rdl ;
JOIN f:\tr ;
ON LOWER(rdl.subdir) = LOWER(tr.n1)

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.

returning emptystring if columnn name not exists

I have a very simple select statement like
SELECT Column-Name
FROM Object
WHERE ID = 123
where the Column-Name is dynamically generated. Is there a possibility to get an empty string if column not exists?
This is a huge hack for SQL Server
SQL is batch based: when submitted to the database engine, the whole batch is parse and a plan compiled. If a column or object does not exist, you'll get an error.
You can test the metadata to see if it exists (COLUMNPROPERTY) then use EXEC to have the SELECT in an separate batch
IF COLUMNPROPERTY(OBJECT_ID('Object'), 'Column-Name', 'ColumnID') IS NOT NULL
EXEC ('SELECT Column-Name FROM Object WHERE ID = 123')
ELSE
SELECT '' AS Column-Name;
Personally, I'd never expect this to be in production code or running on my database servers.
Why not do a desc object or something similar and validate if the column name exists before firing the query?
Otherwise you will end up doing funny things to work around the sql error

Mysterious variable in sql query

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.