"Column not found" when selecting from a table in a different schema - sql

I'm experiencing a very weird issue with H2.
In addition to all the tables residing in default ("PUBLIC") schema, I have several tables created in a separate schema (there's a valid business reason to do it that way, but it's irrelevant here). When I run
select * from schema1.table1
everything works perfectly. If I try to do the same but mention the column name(s) explicitly, e.g.
select col1, col2 from schema1.table1
the query fails with "Column col1 not found; 42S22/42122" error. This occurs whenever the column is referenced anywhere in select (from clause / where clause / etc...).
Column names are correct and they show up in INFORMATION_SCHEMA. Furthermore, if I quote them, query works properly - however this has a side effect of making column names case sensitive which then fails in Hibernate which apparently uppercases them anyway.
Am I overlooking something obvious here? Is there a reason for this bizarre behavior or is this a bug?
Update: Thomas's answer made me realize that the issue was not with a different schema but rather with how tables in that schema were created; specifically the use of quoted identifiers. Here's a script that reproduces the problem in H2 1.3.161 (latest version atm):
create table table1(col1 int, "col2" int);
insert into table1 values(1, 1);
select * from table1; -- works
select col1 from table1; -- works
select "col2" from table1; -- works
select col2 from table1; -- fails
I don't understand why there's a difference between the last 2 queries. Column name is case-sensitive here (because it was defined via quoted identifier), but it does have the correct case. INFORMATION_SCHEMA.COLUMNS shows no differences (aside from name) between the two columns either. Is case insensivity for unquoted columns obtained by forcibly uppercasing all queries?
The above script works as expected (as in all queries complete successfully) in Postgres.

I can't reproduce the problem. Could you post a complete, reproducible problem? I ran the following script in the H2 Console, and it works (meaning, I get no exception):
drop all objects;
create schema schema1;
create table schema1.table1(col1 int, col2 int);
insert into schema1.table1 values(1, 1);
select * from schema1.table1;
select col1, col2 from schema1.table1;

I had the same problem but in my case I was incorrectly using " instead of ' in the query

Related

SQL: temp table "invalid object name" after "USE" statement

I do not fully understand the "USE" statement in Transact-SQL and how it affects the scope of temp tables. I have a user-defined table type in one database but not another, and I've found I need to "USE" that database in order to define a table of that type. Earlier in the query, I define a temporary table. After the "USE" statement, SSMS does not recognize the temp table as a valid object name, however I can still query from it without error.
The skeleton of my SQL query is as follows:
USE MYDATABASE1
[... a bunch of code I did not write...]
SELECT * INTO #TEMP_TABLE FROM #SOME_EARLIER_TEMP_TABLE
USE MYDATABASE2
DECLARE #MYTABLE MyUserDefinedTableType -- this table type only exists in MYDATABASE2
INSERT INTO #MYTABLE(Col1, Col2)
SELECT Col1, Col2 FROM (SELECT * FROM MYDATABASE2.dbo.SOME_TABLE_VALUED_FUNCTION(param1, param2)) T
SELECT A.*, B.Col2
FROM #TEMP_TABLE A
CROSS APPLY DATABASE2.dbo.SOME_OTHER_TABLE_VALUED_FUNCTION(#MYTABLE, A.SomeColumn) B
In the last SELECT statement, SSMS has red squiggly lines under "A.*" and "#TEMP_TABLE", however there is no error running the query.
So my question is: am I doing something "wrong" even though my query still works? Assuming the initial "USE MYDATABASE1" is necessary, what is the correct way to switch databases while still having #TEMP_TABLE available as a valid object name? (Note that moving the definition of #TEMP_TABLE to after "USE MYDATABASE2" would just shift the problem to #SOME_EARLIER_TEMP_TABLE.)
In SQL USE basically tells the query which database is the "default" database.
Temp tables can play tricks on intellisense - unless they're explicitly defined using the CREATE TABLE #MyTempTable route, intellisense doesn't really know what to do with them a lot of the time. Don't worry though - temp tables are scoped to the query.
Although I do feel it's worth pointing out: while UDTs are database specific, you can create an assembly to use across databases

VBA Access Table reference in SQL query

I have been running into trouble executing SQL code in VBA Access when I refer to certain Table names.
For example,
INSERT INTO TempTable (ClientName) SELECT DISTINCT 1_1_xlsx.ClientName FROM 1_1_xlsx'<--does not work
The code works fine when I changed the Table name from 1_1_xlsx to Stuff.
INSERT INTO TempTable (ClientName) SELECT DISTINCT Stuff.ClientName FROM Stuff '<--works
I have no idea why the first query results in a syntax error and the second code is runs fine even when they refer to the same thing. I suspect it should be the naming conventions but I could not find any concrete answers.
Also, are there any ways that I could use 1_1_xlsx as my table name? Or am I just writing my query wrong?
try this:
INSERT INTO TempTable (ClientName) SELECT DISTINCT [1_1_xlsx].ClientName FROM [1_1_xlsx]
In many SQL based databases you can't have a table name or field name that starts with a number.
I suspect this is the underlying reason for your problem. Although Access will allow it, I have seen it cause problems in the past.
The problem is the number at the beginning of the table name. That is bad -- because it confuses the parser.
This is a bad table name, but SQL allows you to define table aliases. And, in this case, you don't even need to repeat the table name. So, here are two simple solutions:
INSERT INTO TempTable (ClientName)
SELECT DISTINCT ClientName
FROM 1_1_xlsx;
Or:
INSERT INTO TempTable (ClientName)
SELECT DISTINCT t.ClientName
FROM 1_1_xlsx as t
There is no reason to use the complete table name as an alias. That just makes the query harder to write and to read.

Create Microsoft SQL Temp Tables (without declaring columns – like Informix)?

I recently changed positions, and came from an Informix database environment, where I could use SQL statements to select one or more columns ... and direct the output to a temporary table. In Informix, for temp tables, I neither had to declare the column names, nor the column lengths (only the name of a temp table) - I could simply write:
select [columnname1, columnname2, columnname3 ..] from
[database.tablename] where... etc. into temp tablename1 with no log;
Note that in Informix, the temp table stores the column names by default... as well as the data types [by virtue of the data-type being stored in the temp table]. So, if the above statement was executed, then a developer could merely write:
select columname1, columnname2, etc. from tablename1
In my experience, I found this method was very useful - for numerous reasons ('slicing/dicing' the data, using various data sources, etc.)... as well as tremendously fast and efficient.
However, now I am using Microsoft SQL Server, I have not found a way (yet) do the same. In SQL Server, I must declare each column, along with its length:
Create table #tablename1 ( column1 numeric(13,0) );
insert into #tablename1(column1) select [column] from
[database.tablename] where …
[Then use the info, as needed]:
select * from #tablename1 [ and do something...]
Drop table #tablename1
Does anyone know of how I could do this and/or set-up this capability in Microsoft SQL Server? I looked at anonymous tables (i.e. Table-Value constructors: http://technet.microsoft.com/en-us/library/dd776382.aspx)... but the guidance stated that declaring the columns was still necessary.
Thanks ahead of time
- jrd
The syntax is :
select [columnname1], [columnname2], [columnname3] into tablename1 from [database].[schema].[tablename] where...
prefix tablename1 with # if you want the table to be temporary
It should be noted that, while you can use the syntax below:
SELECT col1, col2...
INTO #tempTable1
FROM TABLEA
You should also give your calculated columns names as well.
Such that you get:
SELECT col1, col2...,AVG(col9) AS avgCol9
INTO #tempTable1
FROM TABLEA
Its very simple in sql server as well all you have to do is
SELECT Column1, Column2, Column3,...... INTO #Temp
FROM Table_Name
This statement will Create a Temp Table on fly copying Data and DataType all over to the Temp Table. # sign makes this table a temporary table , you can also Create a Table by using the same syntax but with out the # sign, something like this
SELECT Column1, Column2, Column3,...... INTO New_Table_Name
FROM Table_Name

Very simple SQL query on varchar fields with sqlite

I created a table with this schema using sqlite3:
CREATE TABLE monitored_files (file_id INTEGER PRIMARY KEY,file_name VARCHAR(32767),original_relative_dir_path VARCHAR(32767),backupped_relative_dir_path VARCHAR(32767),directory_id INTEGER);
now, I would like to get all the records where original_relative_dir_path is exactly equal to '.', without 's. What I did is this:
select * from monitored_files where original_relative_dir_path='.';
The result is no records even if in the table I have just this record:
1|'P9040479.JPG'|'.'|'.'|1
I read on the web and I see no mistakes in my syntax... I also tried using LIKE '.', but still no results. I'm not an expert of SQL so maybe you can see something wrong?
Thanks!
I see no problem with the statement.
I created the table that you described.
Did an INSERT with the same values that you provided.
And did the query, and also queried without a where clause.
No problems encountered, so I suspect that when you execute your selection, you may not be connected to the correct database.

informix check if table exists and then read the value

I have a table in informix (Version 11.50.UC4) called NextRecordID with just one column called id and it will have one row. What I want to do is copy this value into another table. But don't want my query to fail if this table does not exist. Something like
if table NextRecordID exists
then insert into sometable values ('NextRecordID', (select id from NextRecordID))
else insert into sometable values ('NextRecordID', 1)
I ended up using the below SQL query. Its not ANSI SQL but works the informix server I am using.
insert into sometable values ('NextRecordID',
select case (select 1 from systables where tabname='nextrecordid')
when 1 then (select nextid from nextrecordid)
else (select 1 from systables where tabname='systables') end
from systables where tabname='systables');
What is happening here is within insert query I get the value to be inserted by using select query. Now that select query is interesting. It uses case statement of Informix. I have written a select query to check if the table nextrecordid exists in systables and return 1 if it exists. If this query returns 1, I query the table nextrecordid for the value or else I wrote a query to return the default value 1. This work for me.
You should be able to do this by checking the systables table.
Thank you for including server version information - it makes answering your question easier.
You've not indicated which language(s) you are using.
Normally, though, you design a program to expect a certain schema (certain tables to be present), and then fail - preferably under control - if those tables are not present. Also, it is not clear whether you would get into problems because of repeated execution of the second INSERT statement. Nor is it clear when the NextRecordID table is updated - presumably, once the value has been used, it must be updated.
You should look at SERIAL (BIGSERIAL) and see whether that is appropriate for you.
You should also look at whether a SEQUENCE would be appropriate to use here - it certainly looks rather like it might be applicable.
As Adam Hughes points out, if you want to check whether the NextRecordID table is present in the database, you would look in the systables table. Be aware, though, that your search will need to be against an all lower-case name (nextrecordid).
Also, MODE ANSI databases complicate life - you have to worry about the table's owner (because there could be multiple tables called nextrecordid in a MODE ANSI database). Most likely, you don't have to worry about that - any more than you are likely to have to worry about delimited identifiers for table "someone"."NextRecordID" (which is a different table from someone.NextRecordID).