SQL request from 2 different databases with same structure - sql

I have 2 really similar databases, with exact same structure (one of them is a backup of the other so some values changed which is why they are similar but not the exact same).
So here is what I would like to do, taking value from database 2 and updating database 1 with it (so it will allow me later to backup some data from a certain user without having to do it all manually or to backup everyone)
UPDATE s
SET
t1.column=t2.column
FROM database1.table1 t1
JOIN database2.table1 t2
WHERE t1.table2='test'
AND t2.table2='test'
I tried something like this but it didn't work, both database are in a same server and "next to each others", also names are different, so I wanted to know if what I try to do is possible or not

If table's name is Test, then try this query for Update (instead of key, place column primary key of table) :
Update database1.dbo.test
Set
database1.dbo.test.Column=t2.Column
From
(Select Column,Key from database2.dbo.test) t2
Join database1.dbo.test t1
On t2.Key=t1.Key
Or
UPDATE pereger.dbo.characters
SET
pereger.dbo.characters.level=t2.level FROM
(SELECT level,characterId FROM
peregercopy.dbo.characters) t2
JOIN pereger.dbo.characters t1 ON
t2.characterID=t1.characterId
WHERE t2.characterId=5

Related

Importing sql table (t1) from one db (db1)to another (db2) (t2)and then use t2 to update values of a table in db2

I need a query to import data of a table into a different table and different database. Then using the new table I need to update another table in same database
As you tagged SSMS, I'm assuming you're using SQL Server. This answer may apply to other databases, but you'd need to check.
How to refer to other databases
Assuming your database is on the same server, and the table is in the 'dbo' schema, then you can refer to the other database/table as follows
SELECT *
FROM [db1].[dbo].[t1]
If it's on a different server (but has been set up as a linked server) you can do something similar
SELECT *
FROM [servername].[db1].[dbo].[t1]
Making a copy of the data
To save it as a new table within your current database, you could either create a copy of the table's structure in the current database and use an INSERT INTO command, or instead let SQL Server make the table for you by using the 'INTO' clause in the SELECT e.g.,
SELECT *
INTO [db2].[dbo].[t2] -- Or just simply [t2] if you're running this from that database and are happy with [dbo]
FROM [db1].[dbo].[t1]
The above copies the data from the t1 table in db1 to a new table t2 in db2.
You can then use the data in t2 as you normally would use a table.
If you're running this from within d1, you will always need to refer to the tables in d2 properly (and/or alias them) as below.
UPDATE t3
SET xfield = t2.zfield
FROM [db2].[dbo].[t3] AS t3
INNER JOIN [db2].[dbo].[t2] AS t2 ON t3.id = t2.id

Can i copy data from one database table to another already existing database table sql server?

So i have 2 very similar databases, they are identical except for the data that exists in the tables. I want to copy the data from the EQUIP_MODEL table that exists in the PILOT database to the EQUIP_MODEL table that exists in the DOMAIN database.
Is this even possible? or do i have to do manual inserts for all the data?
You can use fully qualified names in Insert statement
INSERT INTO DOMAIN.SCHEMANAME.EQUIP_MODEL (col1,col2,col3...)
SELECT col1,col2,col3.. FROM PILOT.SCHEMANAME.EQUIP_MODEL
To get the foreign key values (not the exact code you have to alter based on column name and mapping)
INSERT INTO DOMAIN.SCHEMANAME.EQUIP_MODEL
(id,col2,col3)
SELECT sp.id,
col2,
col3
FROM PILOT.SCHEMANAME.EQUIP_MODEL em
JOIN PILOT.SCHEMANAME.Prent_table p
ON em.id = p.id
JOIN DOMAIN.SCHEMANAME.parent_table sp
ON sp.somename_number_col = p.somename_number_col

DB2 SQL Statement for Inserting new data and updating existing data

I've found a lot of near misses on this question. So many similar, but not quite right, scenarios. No doubt my ignorance will shine here.
Using DB2 and a shred of knowledge, my scenario is as follows:
On a table, insert a row of data if a given value is not present in a given column, or update the corresponding row if the value is present.
I have a table
id, bigint, not nullable
ref,varchar, nullable
I am not sure if a MERGE is the correct path here as most examples and thorough discussions all seem to revolve around merging one table into another. I'm simply gathering user input and either adding it or updating it. It seems like it should be really simple.
I'm using jdbc and prepared statements to get this done.
Is MERGE the correct way to do this?
When testing my query in DB2 Control Center, I run up against
"No row was found for FETCH, UPDATE or DELETE; or the result of a
query is an empty table"
or a variety of other errors depending on how I structure my MERGE. Here's what I have presently.
merge into table1 as t1
using (select id from table1 group by id) as t2
on t1.id = t2.id
when matched then update set t1.ref = 'abc'
when not matched then insert (t1.id, t1.ref) values (123, 'abc');
If I were to instead compose an update followed by an insert; for new data the insert runs and the update fails, and for existing data they both succeed resulting in bad data in the table, e.g. two identical rows.
The desired result is if on initial use with the values:
id = 1
ref = a
a new row is added. On subsequent use if the values change to:
id = 1
ref = b
the row with id = 1 is updated. Subsequent uses would follow the same rules.
Please let me know how I can phrase this question better.
Update id is not an automatic incrementing key. It's an external key that will be unique but not every thing we are referencing will need a related row in the table I'm attempting to update. This table is rather unstructured on its own but is part of a larger data model.
I'm a bit puzzled by your query. Reading the text makes me suspect that you want something like this:
merge into table1 as t1
using ( values (123, 'abc') ) as t2 (id, ref)
on t1.id = t2.id
when matched then update
set t1.ref = t2.ref
when not matched then
insert (id, ref) values (t2.id, t2.ref);
Is that correct?

access 2010 append data into table without overwriting existing records

Sorry for the long question/post but need some help as I've been searching for several days but havent found anything that helps. Seems like it should be easy but..here goes
I have table1 in my (Access 2010) database that has exising records. I have another table2 that after I run a query, it first deletes the data in table 2, then imports new records into that table. I run the import into table 2 on a semi regular basis but have yet to copy all those records into table 1 successfully.
I need to copy only the records from table 2 to table 1 if the records don't already exist in table1. So, each time the query or vba code would run, it would be continuing to grow table 1 without duplicating existing data.
To clarify further, it's data from the Outlook GAL so each time table2 imports that data (lname,fname,phone,email) it needs to be added to table1, but only if it doesn't already exist in table 1.
I have a small start of SQL but cannot get it to work properly because I'm not sure how to add the other fields into this SQL statement properly (unfortunately I don't know a whole lot about SQL or creating an append query):
INSERT INTO [Current] ( FirstName )
SELECT DISTINCT tblglobaladdresslistimport.First
FROM tblglobaladdresslistimport LEFT JOIN [Current] ON tblglobaladdresslistimport.First = Current.FirstName
WHERE Current.FirstName Is Null;
How about this :
INSERT INTO [Current](FirstName, LastName, Phone, Email)
SELECT DISTINCT
tblglobaladdresslistimport.First
, tblglobaladdresslistimport.Last
, tblglobaladdresslistimport.Phone
, tblglobaladdresslistimport.Email
FROM
tblglobaladdresslistimport LEFT JOIN [Current]
ON tblglobaladdresslistimport.First = Current.FirstName
AND tblglobaladdresslistimport.Last = Current.LastName
AND tblglobaladdresslistimport.Phone = Current.Phone
AND tblglobaladdresslistimport.Email = Current.Email
WHERE Current.FirstName Is Null
AND Current.LastName Is Null
AND Current.Phone Is Null
AND Current.Email Is Null;
Adjust column names if I guessed it wrong. That assumed that you don't have primary key, so data in tblglobaladdresslistimport considered already exists if there is a row in Current having same value for all columns.

Sql exists copy

I have a mssql stored procedure question for you experts:
I have two tables [table1] which retrieves new entries all the time. I then have another table [table2] which I need to copy the content of [table1] into.
I need to check if some of the the rows already exists in [table2], if it do, just update the Update-timestamp of [table2], otherwise insert it into [table2].
The tables can be rather big, about 100k entries, so which is the fastest way to do this?
It should be noticed that this is a simplified idea, since there is some more datahandling happening when copying new content from [Table1] -> [Table2].
So to sum up:
If a row exist both [Table1] and [Table2] update the timestamp of the row in [Table2] otherwise just insert a new record with the content into [Table1].
If you have SQL Server 2008, it has a MERGE command that can do an insert or update as appropriate.
This works across all versions of SQL Server. MERGE does the same in SQL Server 2008.
UPDATE
table2
SET
timestampcolumn = whatever
WHERE
EXISTS (SELECT *
FROM table1
WHERE
table1.key = table2.key)
INSERT table2 (col1, col2, col3...)
SELECT col1, col2, col3...
FROM table1
WHERE
NOT EXISTS (SELECT *
FROM table2
WHERE
table2.key = table1.key)
Given that this sounds like a ETL Process. Have you considered using SQL Server Integration Services?
If you are planning on export/loading/processing lost of data then this is the way to go in my view. You also have the added advantage of being able to run multiple threads in parallel and more options to tweak your data throughput and server memory utilisation etc.