SQL Server - Syntax around UNION and USE functions - sql

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 ...

Related

Oracle CTE failing in one computer

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;

Is it possible to store data in database using UNION and EXCEPT commands?

Is it possible to store data in database using UNION and EXCEPT commands in query or we have to use INSERT?
If it is possible please tell me how? if not, is it possible to use EXCEPT and UNION with INSERT commands?
I've seen the following link as well.
UNION and EXCEPT are set operations that are used with the SELECT statement. The statements that modify data are:
UPDATE
INSERT
DELETE
MERGE (in some databases)
All of these can accept a SELECT subquery somewhere in the statement. UNION and EXCEPT could be used with that SELECT as part of a larger operation.
How can a new record be unioned or excepted without inserting/storing it into the database likewise How can you store it either with the same. However Insert can be used interchangebly with union and except to store either related columns data or with filtering with except statements. It works when you manually have to enter the data but if you want to extract and insert then you require use of select as well.

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 or trick to search through whole database

is there a way to actually query the database in a such a way to search for a particular value in every table across the whole database ?
Something like a file search in Eclipse, it searches accross the whole worspace and project ?
Sorry about that .. its MS SQL 2005
SQL Workbench/J has a built in tool and command to do that.
It's JDBC based and should also work with SQL Server.
You will need to use the LIKE operator, and search through each field separately. i.e.
SELECT * FROM <table name>
WHERE (<field name1> LIKE '%<search value>%') OR
(<field name2> LIKE '%<search value>%') OR
... etc.
This isn't a quick way though.
I think the best way would be to
1) programatically generate the query and run it
2) use a GUI tool for the SQL server you are using which provides this functionality.
In mysql you can use union operator like
(SELECT * from table A where name = 'abc') UNION (SELECT * from
table B where middlename = 'pqr')
and so on
use full text search for efficency
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Well, your best bet is to write a procedure to do this. But to give you some pointers you can use the INFORMATION_SCHEMA.Tables to get a list of all the tables in a given database and INFORMATION_SCHEMA.Columns to get a list of all columns. These tables also give you the datatype of columns. So you will need a few loops on these tables to do the magic.
It should be mentioned most RDBMSs nowadays support these schemas.
In phpmyadmin, go to your database, reach the search tab.
Here you will be able to select all of your tables and search through your entire db in one time.

How do I construct a cross database query in MySQL?

I've got two databases on the same server. The Google gave me some hints but there wasn't anything "official" that I could find. Could someone point me to the documentation that explains how to do this? An explanation using PHP would be useful as well. Thanks!
I've got two databases on the same server. ...How do I construct a cross database query in MySQL?
You access other databases on the same MySQL instance by prefixing the table with the appropriate database name. IE:
SELECT *
FROM this_database.table_1 t1
JOIN that_database.table_2 t2 ON t2.column = t1.column
Keep in mind
A query executes with the credentials of the authentication used to set up the
connection. If you want to query two tables simultaneously across two (or more)
databases, the user used to run the query will need SELECT access to all
databases involved.
Reference:
Identity Qualifiers
SELECT * FROM DB1.myTable1 AS db1, DB2.myTable2 AS db2
http://www.dottedidesign.com/node/14 provides the following example:
SELECT
arbogast.node.nid as anid,
mcguffin.node.nid as mnid,
arbogast.node.title as atitle,
mcguffin.node.title as mtitle
FROM arbogast.node, mcguffin.node
WHERE arbogast.node.nid = 1
AND mcguffin.node.nid = arbogast.node.nid;
Where arbogast and mcguffin are different databases.