Oracle CTE failing in one computer - sql

I have queries created in Microsoft Query to run in Excel with VBA.
They work in different computers but there's one computer where it doesn't work.
In that computer the queries still work except the ones that use CTEs.
A normal query like the following works:
SELECT
TBL.COL
FROM
DB.TBL TBL;
But when it has a subquery (CTE) like the following:
WITH
SUBQUERY AS (
SELECT
TBL.COL
FROM
DB.TBL TBL
)
SELECT
SUBQUERY.COL
FROM
SUBQUERY;
It runs but doesn't retrieve any data.
It doesn't even show the column name like it would if it worked but had 0 records returned.
The query shows the warning message:
SQL Query can't be represented graphically. Continue anyway?
Which is normal and shows in any computer, but it also shows another warning message after:
SQL statement executed successfully.
Which only appears in that computer when it doesn't work.
I need to be able to use them for the queries that I have made.
Using temporary tables would maybe work but I don't have the permissions required to try.
I tried using inline views but they duplicate the data.

I have queries created in Microsoft Query to run in Excel with VBA.
... but there's one computer where it doesn't work.
Common table expressions (i.e., the WITH clause) were not introduced until release 9 of the database. Since ODBC is involved (Microsoft Query), the most likely reason for your situation is that the computer that does not work has an out-dated (pre-release 9) version of the Oracle Client installed.
Compare the Oracle Client installations between a client computer that works and one that does not, to find whether this is the case. If it is, upgrade the Oracle Client on the problematic machine.

I think you can use...
SELECT
SUBQUERY.COL
FROM
(
SELECT
TBL.COL AS COL --or (TBL.COL COL) or ( COL ) #if not duplicate with any
FROM
DB.TBL TBL
) SUBQUERY;

Related

SQL multiple tables - very slow

I am trying to fasten up a SQL Server report regarding the IBM OS/400 operating system for my sales department.
A colleague of mine (which left the company) did this report and used a ton of sub selects.
The report usually takes about 30 min to process and often just fails to be displayed. I already tried to cut out some tables/rows in hopes of fastening up the process without success (all is needed by the sales department).
It works over all relevant data (orders, customers, articles, our order at the manufacturer, the manufacturer and so on). Any ideas?
I can't index it, due to the OS/400 system; guess it would be a new programming task for our contractor which leads to costs.
Can I use some clever joins? or somehow reduce the amount of subselects?
Are you using 4 part names in your query? That's probably your problem...
From SQL server...
-- Pull all rows from the table(s) back to MS SQL server and do the where locally on the MS SQL server
select * from LINKEDSVR.MYIBMI.MYLIB.MYTBL where locnbr = '00335';
-- Sends the statement to IBM i server for processing, only results are returned..
select * from openquery(LINKEDSVR, 'select * from MYTBL where locnbr = ''00335''');
Try running the subselects first, sending the output of each to its own table.
Update statistics on the tables. Then run the rest of the SQL, replacing what were originally subselects with the tables created in the first step.
Treat multiple layers of nesting the same way: each layer is its own insert into another table.
I've found that query optimizers have a hard time with complex SQL. Breaking-out the subqueries into separate steps often resolves this.
Between runs my preference is to leave the data intact as a reference in case debugging is needed, then truncate the tables as the first step of a run.
Responding to eraser's comments
Assuming your original query takes this general form:
select [columns] from
(-- subquery
select [columns] from TableA
) as Subquery
from TableB
where mainquery_where_clause
Re-write:
-- Create a table to handle results for your subquery:
Create Table A ;
-- Update the data distribution statistics:
update stats (TableA) ;
-- Now run the subquery:
insert into SubQTable select [columns] from TableA
-- Now run the re-written main query:
Select [columns]
from TableA, TableB
where TableA.joincol = TableB.joincol
and mainquery_where_clause ;
I noticed some syntax issues with the SQL you posted. Looks like something got left out. But the principle of my answer remains the same. Please note that applying my suggestion may not help, as there are potentially many variables to your scenario; you mentioned subqueries, so I chose to address that.
Halfer's suggestion is a great one: edit your original question, adding the SQL code, and putting it in the "{}" supplied by the text editing tool.
I strongly suggest that you obtain the SQL execution plan and post the results.

SQL Server - Syntax around UNION and USE functions

have a series of databases on the same server which i am wishing to query. I am using the same code to query the database and would like the results to appear in a single list.
I am using 'USE' to specify which database to query, followed by creating some temporary tables to group my data, before using a final SELECT statement to bring together all the data from the database.
I am then using UNION, followed by a second USE command for the next database and so on.
SQL Server is showing a syntax error on the word 'UNION' but does not give any assistance as to the source of the problem.
Is it possible that I am missing a character. At present I am not using ( or ) anywhere.
The USE statement just redirects your session to connect to a different database on the same instance, you don't actually need to switch from database to database in this matter (there are a few rare exceptions tho).
Use the 3 part notation to join your result sets. You can do this while being connected to any database.
SELECT
SomeColumn = T.SomeColumn
FROM
FirstDatabase.Schema.TableName AS T
UNION ALL
SELECT
SomeColumn = T.SomeColumn
FROM
SecondDatabase.Schema.YetAnotherTable AS T
The engine will automatically check for your login's users on each database and validate your permissions on the underlying tables or views.
UNION adds result sets together, you can't issue another operation (like USE) other than SELECT between UNION.
You should use the database names before the table name:
SELECT valueFromBase1
FROM `database1`.`table1`
WHERE ...
UNION
SELECT valueFromBase2
FROM `database2`.`table2`
WHERE ...

Why is MS Access 2010 SQL choking on this query?

The following query will not show up in design view and if you trying to make it show it locks up MS Access and you have to use the Task Manager to stop MS Access. The query actually runs and produces the correct results. If there is a better way I will certainly accept that.
SELECT
log_metric_N.metric_title,
log_metric_N.metric_N
FROM
(
SELECT
tref_log_metrics_weights_and_factors.metric_title,
[metric_base].[metric_count],
[metric_base].[metric_sum],
(([metric_base].[metric_count]*[tref_log_metrics_weights_and_factors].[metric_weight])/[metric_base].[metric_sum]) AS metric_N
FROM
tref_log_metrics_weights_and_factors,
(
SELECT
Count(tref_log_metrics_weights_and_factors.metric_weight) AS metric_count,
Sum(tref_log_metrics_weights_and_factors.metric_weight) AS metric_sum
FROM
tref_log_metrics_weights_and_factors
WHERE (((tref_log_metrics_weights_and_factors.metric_weight)<>0))
) as metric_base
) AS log_metric_N;
#HansUp you were exactly right on. I forgot all about the Domain functions and they work perfectly without the complexity. Below is the resultant SQL statement.
SELECT
tref_log_metrics_weights_and_factors.metric_title,
DCount("[metric_weight]","tref_log_metrics_weights_and_factors","[metric_weight]<>0") AS metric_count,
Dsum("[metric_weight]","tref_log_metrics_weights_and_factors") AS metric_sum,
(([metric_count]*[tref_log_metrics_weights_and_factors].[metric_weight])/[metric_sum]) AS metric_N
FROM
tref_log_metrics_weights_and_factors

Select * not returning all columns - Coldfusion / SQL Server 2008

I am getting some strange behavior involving database queries that I have never seen before and I'm hoping you can illuminate the issue.
I have a table of data called myTable with some columns; thus far everything involving it has been fine. Now, I've just added a column called subTitle; and II notice that the SELECT * Query that pulls in the data for a given record is not aware of that column (it says the returned query does not have a subTitle column), but if I explicitly name the column (select subTitle) it is. I thought perhaps that the Coldfusion server might be caching the query so I tried to work around with cachedwithin="#CreateTimeSpan(0, 0, 0, 0)#" but no dice.
Consider the below code:
<cfquery name="getSub" datasource="#Application.datasourceName#">
SELECT subTitle
FROM myTable
WHERE RecordID = '674'
</cfquery>
<cfoutput>#getSub.subTitle#</cfoutput>
<cfquery name="getInfo" datasource="#Application.datasourceName#">
SELECT *
FROM myTable
WHERE RecordID = '674'
</cfquery>
<cfoutput>#getInfo.subTitle#</cfoutput>
Keeping in mind that record 674 has the string "test" in it's subTitle column the about of the above is
test
[[CRASH WITH ERROR]]
This doesn't make sense to me unless SQL Server 2008 has somehow cached the SELECT * query with the previous incarnation of the table, but the strange thing is if I run the query right from within SQL Management Studio there are no problems and it shows all columns with the select *
Frankly this one has me baffled; I know I can get around this by explicitly naming all the desired columns in the select query instead of using * (which is best practice anyway), but I want to understand why this is occurring.
I've worked with SQL Server 2005 for many years and never had something like this happen, which leads me to believe it might involve something new in SQL Server 2008; but then again the fact that the query works fine inside of the management studio doesn't jive with that either.
===UPDATE===
Clearing the Template Cache in the CF admin will solve the issue
Yes, ColdFusion caches the <cfquery> SQL string. If the underlying table structure changes, the result might be an exception like you see it.
Work-arounds:
Recommended solutiuons:
If you have the development or enterprise version you can view your query cache in the server moniter and clear only the queries there. (comment from #Dpolehonski, thanks)
Otherwise, click Clear Template Cache Now in the ColdFusion Administrator (under Server Settings/Caching).
This will invalidate all cached CFML-Templates on the server and CF will re-compile them when necessary.
Quick and dirty:
Subtly change the query SQL, for example add a space somewhere. When you are on a development machine it's the quickest way to fix the issue.
This will invalidate the compiled version of this query only and force a re-compile.
(Note that removing the subtle change will trigger the error again since the old query text will remain cached.)
Brute-force:
Re-start the ColdFusion server. Brutal, but effective.
Or the quick and super dirty method:
<cfquery name="getInfo" datasource="#Application.datasourceName#">
SELECT
*, #createUUID()# as starQueryCacheFix
FROM
myTable
WHERE
RecordID = '674'
</cfquery>
Don't leave in production code though... it'll obsolete all of the query caching ColdFusion does. I did say it was super dirty ;)

Access 2007 to Oracle 10g linked table -- query with flawed results, but no errors thrown

Access 2007 databases querying linked oracle 10g tables are returning flawed result sets when using the WHERE clause to filter-out unwanted records. Oddly, some filtering is happening, but not reliably.
I can reliably demonstrate/produce the problem like this:
Create a *new* database with Access 2007.
Create a second *new* database with Access 2007, and then "save-as" 2000.
Create a third *new* database with an older version of Access.
Run the following query in each database:
SELECT
STATUS,
ID,
LAST_NAME,
FIRST_NAME
FROM
Oracle10g_table
WHERE
STATUS="A"
In both databases created with Access 2007, running this query will give you a result set in which some of the records where (STATUS="A") = false have been filtered out, but not all of them.
In databases created with older versions of access, the where clause filters properly, and the result set is correct.
STATUS is a text field
The table is a "linked" table to an Oracle10g Database
The table has 68k rows
I've tested my timeout at 60, 1000 and 0
Has anyone run into this problem?
I wonder if this is a new "feature" of access that will also affect 2010. Could this have anything to do with ODBC?
Thanks for any help,
- dave
MORE...
I just tried an alternate form of the query, using HAVING instead of WHERE, and it worked! Problem is, besides that this shouldn't change anything (yes -- more virtual tables, but shouldn't change the end result) my end-users will be using the Access 2007 visual query designer, not typing SQL directly, which is going to default any criteria they enter into a WHERE.
My hunch is that one of your ODBC drivers used by Access to connect to Oracle is treating "A" as a column name not the literal 'A'. Have you tried single quotes on the 'A'? In Oracle double quotes are used to reference column names, is there a column named "A" by any chance?
Oracle Query Example #1
Select object_name from all_objects
where "OBJECT_NAME" = 'DUAL'
Oracle Query Example #2
with example as (
Select object_name as "Fancy Column Name" from all_objects
)
select * from example
where "Fancy Column Name" = 'DUAL'
I've had a similar problem. In my case, changing the ODBC driver worked, but I could also just change the 'unique record identifier' to a column with no nulls in it. It still doesn't have to be the "right" unique record identifier.
This turned-out to be an ODBC-related issue. Our tech support service unit installs connectivity on each of our workstations -- they program it themselves, and who knows what they actually put into it -- but the net result is that when you link to an ODBC datasource with Access (of any version), our network servers show-up in the 'machine data source' tab, so we just click on the one we want and away we go. This has worked well until Access 2007.
What I did was create a "new" machine data source, which let me choose the ODBC driver myself (instead of making me use the one our tech support folks created). I picked "Microsoft ODBC for Oracle", entered the name of the server I wanted, and that all it took. Now the WHERE-clause inconsistent filtering problem is solved (I hope).
The only thing remaining is to send this back to our tech support folks, so they can clean-up their installation. Should I ask for hazard pay? :-) hehe