Please consider the following:
use db1;
select * into #db1_tmp from mytable;
use db2;
select * into #db2_tmp from myothertable;
-- join temp table 1 and 2
select * from #db1_tmp a
left join db2_tmp b on where a.uid = b.uid;
This works, but SQL Server Management Studio is red-underlining #db1_tmp in the last query and therefore in all other statements that depend on this table.
Question: what is the proper way to access a temp table created in another database to prevent this underlining from happening? I tried db1.#db1_tmp but this does not work. I'm on SQL Server 2008.
Temp tables actually appear in their own database, TempDB. I think the root of your issue is the use statements. Try this instead:
select * into #db1_tmp from db1.dbo.mytable;
select * into #db2_tmp from db2.dbo.myothertable;
-- join temp table 1 and 2
select * from #db1_tmp a
left join db2_tmp b on where a.uid = b.uid;
But if this is the extent of what you're doing (creating the temp tables just to do a join across the databases), you can skip the temp tables altogether:
select * from db1.dbo.mytable a join db2.dbo.myothertable b on a.uid = b.uid.
Temp tables has no use of Database reference for creation so gets created in tempdb.
Only the source can be changed with "use" or "dbname.dbo.mytable".
The red-underlining is due to intellisense. The temp table is just identified as a normal table before execution and redlined due to database change.
Note: The select query at the last has syntax errors.
it should be,
select * from #db1_tmp a left join #db2_tmp b on a.uid = b.uid;
Related
I am working with AS400 version 7.1.
Having the following:
ServerA (SA) - DatabaseA (DBA) - TableA (TA)
ServerB (SB) - DataBaseB (DBB) - TableB (TB)
SELECT A.*, B.*
FROM SA.DBA.TA A INNER JOIN SB.DBB.TB
ON A.PN=B.PN
WHERE A.PN='BFDKS';
What's the correct syntax to join 2 tables from two different servers in AS400?
I am getting the following error
Relational database SA not in relational database directory
I'm pretty sure this is not currently possible with Db2 for i...
3-part names are new to the i, and as far as I know are limited to
insert into mylib.mytable
(select * from remotedb.somelib.sometable);
see CREATE TABLE with remote subselect
Or in a trigger program..
see 3-part names in triggers
Db2 for LUW has such federation capabilities...
One work around I've seen is the use of a user defined table function (UDTF) to return rows from a remote Db2 for i database..
Not possible on DB2 for i. But like says Charles, you can do it :
-- run this instructions on server B
create table qtemp.SADBATA as (
SELECT A.* FROM SA.DBA.TA A
where A.PN='BFDKS'
) with data;
SELECT * FROM qtemp.SADBATA A INNER JOIN SB.DBB.TB ON A.PN=B.PN;
I have many tables that are all named similarly (like "table1" "table2" "table3" etc.) and I need to use all of them in a query. They all contain the same two variables ("ID" and "date") that they are joined on.
There are at least 25 tables of this sort and I have read-only access to the database so I can't combine them or even create a view that would do so.
My question is: Is there a simple shortcut I can use to join all these tables? If this were SAS I would create a macro, but I'm using Microsoft SQL Server Management Studio 2012.
Instead of having to do this:
select *
from table1 a
join table2 b on a.id=b.id and a.date=b.date
join table3 c on b.id=c.id and b.date=c.date
join ....
join ....
join table25 y on x.id=y.id and x.date=y.date
I'd like to do something like:
select *
from merge(table1 - table25) using(id, date)
Replacing the "merge" statement above with whatever is appropriate. Is such a thing possible?
As pointed out in the comments, the succinct syntax you are looking for doesn't exist.
The only way to shorten the SQL that takes advantage of the fact that the joining columns are all named the same would involve using the using keyword:
select *
from table1 a
join table2 b using (id, date)
join table3 c using (id, date)
join ....
join ....
join table25 y using (id, date)
But sadly, even that won't work for you, because the using keyword is not recognized in SQL Server. It does work in other popular databases though.
Struggling with a create table statement which is based on this select into statement below:
#MaxAPDRefundAmount money = 13.00
...
select pkd.*, pd.ProviderReference, per.FirstName, per.Surname, #MaxAPDRefundAmount [MaxAPDRefundAmount],commission.Type [Commission] into #StagedData from CTE_PackageData pkd
inner join J2H.dbo.Package pk on pkd.Reference = pk.Reference
inner join J2H.dbo.Product pd on pk.PackageId = pd.PackageId
inner join J2H.dbo.FlightReservation fr on pd.ProductId = fr.ProductId
and fr.FlightBoundID = 1
inner join J2H.dbo.ProductPerson pp on pd.ProductId = pp.ProductID
and pp.StatusId < 7
inner join J2H.dbo.Flight f on fr.FlightId = f.FlightID
inner join J2H.dbo.Person per on pk.PackageId = per.PackageId
and per.PersonId = pp.PersonId
inner join J2H.dbo.PersonType pt on per.PersonTypeId = pt.PersonTypeID
We are changing a select into to just normal insert and select, so need a create table (we are going to create a temp (hash tag table) and not declaring a variable table. Also there is a pkd.* at the start as well so I am confused in knowing which fields to include in the create table. Do I include all the fields in the select statement into the create statement?
Update:
So virtually I know I need to include the data types below but I can just do:
create table #StagedData
(
pkd.*,
pd.ProviderReference,
per.FirstName,
per.Surname,
#MaxAPDRefundAmount [MaxAPDRefundAmount],
commission
)
"Do I include all the fields in the select statement into the create statement?" Well, that depends, if you need them, than yes, if not than no. It's impossible for us to say whether you need them... If you're running this exact query as insert, than yes.
As for the create statement, you can run the query you have, but replace into #StagedData with something like into TEMP_StagedData. In management studio you can let sql server build the create query for you: right-click the newly created TEMP_StagedData table in the object explorer (remember to refresh), script Table as, CREATE To and select New Query Editor Window.
The documentation of the CREATE TABLE statement is pretty straightforward.
No. Clearly, you cannot use pkd.* in a create table statement.
What you can do is run your old SELECT INTO statement as a straight SELECT (remove the INTO #stagedata) part, and look at the columns that get returned by the SELECT.
Then write a CREATE TABLE statement that includes those columns.
To create a table from a SELECT without inserting data, add a WHERE clause that never returns True.
Like this:
SELECT * INTO #TempTable FROM Table WHERE 1=0
Once the table with the columns for your SELECT, you can add additional columns with ALTER TABLE.
ALTER TABLE #TempTable ALL ExtraColumn INT
Then do your INSERT/SELECT.
I am loading data into a parent-child pair of tables in a "staging" database schema. If there are duplicate records that were previously loaded into a parent-child pair of tables in a "master" database schema, I want to delete them from the "staging" database tables.
This query
SELECT A.*,B.*
FROM STG.AUTO_REPR_PAR_STG A
JOIN STG.AUTO_REPR_CHLD_STG B
ON A.TEST_SEQ_NUM=B.TEST_SEQ_NUM
WHERE EXISTS ( SELECT A.*, B.*
FROM MST.AUTO_REPR_PAR A
JOIN MST.AUTO_REPR_CHLD B
ON A.TEST_SEQ_NUM=B.TEST_SEQ_NUM
)
will show what's in staging that was previously loaded in master. But how do I delete from the parent-child pair of tables in staging database? I am drawing a "blank"....I tried this but it bombs ("Tables not allowed in FROM clause"):
DELETE FROM STG.AUTO_REPR_PAR_STG A
JOIN STG.AUTO_REPR_CHLD_STG B
ON A.TEST_SEQ_NUM=B.TEST_SEQ_NUM
WHERE EXISTS (SELECT A.*, B.*
FROM MST.AUTO_REPR_PAR A
JOIN MST.AUTO_REPR_CHLD B
ON A.TEST_SEQ_NUM=B.TEST_SEQ_NUM
)
Back-end is Teradata v13. I am currently researching the CASCADE DELETE option but I am not even sure it is supported....Any idea?
There's no way to delete from multiple tables in a single DELETE statement, you need one for each table:
DELETE FROM STG.AUTO_REPR_PAR_STG A
WHERE TEST_SEQ_NUM IN (
SELECT A.TEST_SEQ_NUM FROM MST.AUTO_REPR_PAR A JOIN MST.AUTO_REPR_CHLD B
ON A.TEST_SEQ_NUM=B.TEST_SEQ_NUM )
;DELETE FROM STG.AUTO_REPR_CHLD_STG B
WHERE TEST_SEQ_NUM IN (
SELECT A.TEST_SEQ_NUM FROM MST.AUTO_REPR_PAR A JOIN MST.AUTO_REPR_CHLD B
ON A.TEST_SEQ_NUM=B.TEST_SEQ_NUM )
If you run this as a Multi Statement Request the join will be done only once.
You may try something like this:
Instead of a subquery with the EXIST clause, you can use an OUTER JOIN - you select all rows with NULL columns in the target outer table, i.e. the not-matching rows;
You save the result of the the previous query into a temporary table, and you run 2 DELETE statements.
An OUTER JOIN is much more efficient compared to a subquery with EXISTS, especially with large data sets.
I am working with the code below but it is returning an error -
Incorrect syntax near the keyword 'AS'
I expect the query to create a table using the data from existing tables.
create table Allactivity as
(
select dbo.dim_client.*,dbo.dim_transaction.*
from dbo.dim_client,dbo.dim_transaction,dbo.fact_capital
where dbo.dim_client.dim_client_key=dbo.fact_capital.dim_client_key
and dbo.dim_transaction.dim_transaction_key=dbo.fact_capital.dim_transaction_key
)
It looks like you're using Microsoft SQL Server. T-SQL has a different syntax: SELECT INTO:
http://msdn.microsoft.com/en-us/library/ms190750.aspx
select dbo.dim_client.*,dbo.dim_transaction.*
into Allactivity
from dbo.dim_client,dbo.dim_transaction,dbo.fact_capital
where dbo.dim_client.dim_client_key=dbo.fact_capital.dim_client_key
and dbo.dim_transaction.dim_transaction_key=dbo.fact_capital.dim_transaction_key
If you use the select into syntax, you will need to have rights to dynamically create a table.
Another solution is to work with a DBA to create the staging table ahead of time. Then clear and load the staging table each time. Have the DBA give you or the application rights to the table. This can be db_datareader & db_datawriter which is a-lot less access than db_owner!
I did notice that you are using older syntax for joins, you should use the newer syntax for forward compatibility.
http://www.straightpathsql.com/archives/2012/11/sql-server-join-syntax-its/
--
-- DBA - Create empty new table (assumes stage schema exists)
--
select
dc.*,
dt.*
into
stage.all_activity
from
dbo.fact_capital as fc
left join
dbo.dim_client as dc
on fc.dim_client_key = dc.dim_client_key
left join
dbo.dim_transaction as dt
on fc.dim_transaction_key = dt.dim_transaction_key
where (1 = 0);
-- User/Application - clear the table
delete from stage.all_activity;
-- User/Application - add some data (+ where clause for range)
insert into
stage.all_activity
select
dc.*,
dt.*
from
dbo.fact_capital as fc
left join
dbo.dim_client as dc
on fc.dim_client_key = dc.dim_client_key
left join
dbo.dim_transaction as dt
on fc.dim_transaction_key = dt.dim_transaction_key;