SQL Insert/Update Issue - sql

I am trying to update one table from another, im able to update fine as long as the customer record exists, but there are some entries that dont.
To solve this i've tried running the following insert
SELECT *
INTO SalBudgetCust
FROM SalBudgetCust_temp
WHERE NOT EXISTS (
SELECT Customer
FROM SalBudgetCust
WHERE Customer = SalBudgetCust_temp.Customer
)
but im prompted with
There is already an object named 'SalBudgetCust' in the database.
Im stuck at this point... could anyone offer a little guideance?

SELECT INTO implicitly creates the table you name. You should instead use INSERT INTO ... SELECT * FROM ..., so that the existing table is used.

It should be INSERT INTO instead of SELECT * INTO ... like
INSERT INTO SalBudgetCust SELECT * FROM SalBudgetCust_temp
WHERE NOT EXISTS
(
SELECT Customer FROM SalBudgetCust WHERE Customer = SalBudgetCust_temp.Customer
)

The general syntax to insert data of one table into another is :
INSERT INTO new_table
SELECT * FROM old_table
WHERE some_condition;
Where, new_table is the table where you want to insert data, old_table is table from where you are fetching data and some_condition is the expression / condition based upon which you want to fetch data from old table.
You may use other clauses like order by, group by, and even sub queries after where clause.
May refer this SQL INSERT INTO and it's subsequent pages.

Related

Insert Statement - From Temp Table

I am currently trying to insert data into a Redshift table from multiple temporary tables that I have created.
Insert into schema.table1 (
with a as (
select t1.country_code, t1.country_name
from t1
)
select * from a
);
The error that I get on this statement says the following: Amazon Invalid operation: syntax error at or near "as";. What do I need to change in order to be able to insert data from a temp table?
Is it not possible to run the command like this if you have same table structures in both schema.table1 and t1
insert into schema.table1
select t1.country_code, t1.country_name
from t1;
One other thing you might want to check is, in your SQL table1 is in 'schema' but t1 is referred without a schema so it's in public, make sure you don't have two t1s with different structures.
I just tried this and it worked for me.
insert into tempt1 ( with a as (select a from tempt2) select * from a);

Postgresql, Copy data to a new table from a foreign table

I'm trying to do a job that will copy data from a foreign table called "m_aduana" of the schema "nathalia" to my schema "publico" and my table "mae_aduana".
I need to do a query that copies all the values from the table "m_aduana" avoiding duplicates.
I got something like this for now but the result sends me an Insert 0 0, which means nothing is inserted.
insert into publico.mae_aduana(cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana)
select cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana
from nathalia.m_aduana
where not exists (
select * from publico.mae_aduana ma_ad, nathalia.m_aduana m_ad
where ma_ad.cod_aduana = m_ad.cod_aduana)
I think you have an error in the inner select. You don't need to use again the table nathalia.m_aduana. If should be something like:
insert into publico.mae_aduana(cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana)
select cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana
from nathalia.m_aduana
where not exists (
select * from publico.mae_aduana ma_ad
where ma_ad.cod_aduana = nathalia.m_aduana.cod_aduana)
You might want to change the where exists part like below
from nathalia.m_aduana m
where not exists (
select 1 from publico.mae_aduana
where cod_aduana = m.cod_aduana)

Openquery statement in SQL Server

I am fairly new to SQL, and I am hoping someone can help me with a problem I'm having. I haven't been able to find any answers helping me figure out this exact problem.
I have two tables in two SQL Server databases on two different servers that I want to compare using the column ItemID. I want to find records from Table1 that have an ItemID that does not exist in Table2 and insert those into a table variable. I have the following code:
--Create table variable to hold query results
DECLARE #ItemIDTable TABLE
(
[itemid][NVARCHAR](20) NULL
);
--Query data and insert results into table variable
INSERT INTO #ItemIDTable
([itemid])
SELECT a.[itemid]
FROM database1.dbo.table1 a
WHERE NOT EXISTS (SELECT 1
FROM [Database2].[dbo].[table2]
WHERE a.itemid = [Database2].[dbo].[table2].[itemid])
ORDER BY itemid
This works on a test server where the two databases are on the same server, but not in real life where they are on different servers. I tried the following using OPENQUERY, but I know I haven't got it quite right.
--Create table variable to hold query results
DECLARE #ItemIDTable TABLE
(
[ItemID][nvarchar](20) NULL
);
--Query data and insert results into table variable
INSERT INTO #ItemIDTable
([ItemID])
SELECT a.[ItemID]
FROM Database1.dbo.Table1 a
WHERE NOT EXISTS (SELECT 1
FROM OPENQUERY([Server2], SELECT * FROM [Database2].[dbo].[Table2]')
WHERE a.ItemID = [Database2].[dbo].[Table2].[ItemID])
ORDER BY ItemID
I'm pretty sure I need to do something in the WHERE clause, where I have the two databases on two servers, I'm just not quite sure how to structure it. Could anyone help?
You can't create an OPENQUERY that is correlated to an outer query. You could populate a temp table with the results of an OPENQUERY and do your WHERE NOT EXISTS against the temp table, or you might want to look into Synonyms.
Openquery works like this:
select *
from openquery
(LINKED_SERVER_NAME,
'select query goes here'
)
Note that the sql portion is single quoted. That means you might have to quote the quotes if necessary. For example:
select *
from openquery
(LINKED_SERVER_NAME,
'
select SomeTextField
from SomeTable
where SomeDateField = ''20141014''
'
)

Update multiple columns in a TABLE from another TABLE (Oracle)

I would like to update multiple columns in one table based on values in another.
I think I know how to write an update statement in T-SQL that does what I want (haven't tested the below). Problem is I'm trying to translate this for an Oracle database. Does anyone know how to do the following in Oracle:
UPDATE oldauth SET
AUTHUNIQUENAME=newauth.AUTHUNIQUENAME
DESCRIPTION=newauth.DESCRIPTION
MAPPINGAUTHNAME=newauth.MAPPINGAUTHNAME
FROM
(SELECT * FROM USERS1 WHERE AUTHSOURCEID=100) oldauth
LEFT JOIN
(SELECT * FROM USERS2 WHERE AUTHSOURCEID=200) newauth
ON
oldauth.AUTHUSERNAME=newauth.AUTHUSERNAME;
MERGE
INTO (
SELECT *
FROM users1
WHERE AUTHSOURCEID=100
) oldauth
USING (
SELECT *
FROM users2
WHERE AUTHSOURCEID=200
) newauth
ON oldauth.AUTHUSERNAME=newauth.AUTHUSERNAME
WHEN MATCHED THEN
UPDATE
SET AUTHUNIQUENAME=newauth.AUTHUNIQUENAME,
DESCRIPTION=newauth.DESCRIPTION,
MAPPINGAUTHNAME=newauth.MAPPINGAUTHNAME

Alternative SQL ways of looking up multiple items of known IDs?

Is there a better solution to the problem of looking up multiple known IDs in a table:
SELECT * FROM some_table WHERE id='1001' OR id='2002' OR id='3003' OR ...
I can have several hundreds of known items. Ideas?
SELECT * FROM some_table WHERE ID IN ('1001', '1002', '1003')
and if your known IDs are coming from another table
SELECT * FROM some_table WHERE ID IN (
SELECT KnownID FROM some_other_table WHERE someCondition
)
The first (naive) option:
SELECT * FROM some_table WHERE id IN ('1001', '2002', '3003' ... )
However, we should be able to do better. IN is very bad when you have a lot of items, and you mentioned hundreds of these ids. What creates them? Where do they come from? Can you write a query that returns this list? If so:
SELECT *
FROM some_table
INNER JOIN ( your query here) filter ON some_table.id=filter.id
See Arrays and Lists in SQL Server 2005
ORs are notoriously slow in SQL.
Your question is short on specifics, but depending on your requirements and constraints I would build a look-up table with your IDs and use the EXISTS predicate:
select t.id from some_table t
where EXISTS (select * from lookup_table l where t.id = l.id)
For a fixed set of IDs you can do:
SELECT * FROM some_table WHERE id IN (1001, 2002, 3003);
For a set that changes each time, you might want to create a table to hold them and then query:
SELECT * FROM some_table WHERE id IN
(SELECT id FROM selected_ids WHERE key=123);
Another approach is to use collections - the syntax for this will depend on your DBMS.
Finally, there is always this "kludgy" approach:
SELECT * FROM some_table WHERE '|1001|2002|3003|' LIKE '%|' || id || '|%';
In Oracle, I always put the id's into a TEMPORARY TABLE to perform massive SELECT's and DML operations:
CREATE GLOBAL TEMPORARY TABLE t_temp (id INT)
SELECT *
FROM mytable
WHERE mytable.id IN
(
SELECT id
FROM t_temp
)
You can fill the temporary table in a single client-server roundtrip using Oracle collection types.
We have a similar issue in an application written for MS SQL Server 7. Although I dislike the solution used, we're not aware of anything better...
'Better' solutions exist in 2008 as far as I know, but we have Zero clients using that :)
We created a table valued user defined function that takes a comma delimited string of IDs, and returns a table of IDs. The SQL then reads reasonably well, and none of it is dynamic, but there is still the annoying double overhead:
1. Client concatenates the IDs into the string
2. SQL Server parses the string to create a table of IDs
There are lots of ways of turning '1,2,3,4,5' into a table of IDs, but the Stored Procedure which uses the function ends up looking like...
CREATE PROCEDURE my_road_to_hell #IDs AS VARCHAR(8000)
AS
BEGIN
SELECT
*
FROM
myTable
INNER JOIN
dbo.fn_split_list(#IDs) AS [IDs]
ON [IDs].id = myTable.id
END
The fastest is to put the ids in another table and JOIN
SELECT some_table.*
FROM some_table INNER JOIN some_other_table ON some_table.id = some_other_table.id
where some_other_table would have just one field (ids) and all values would be unique