Update a "main" table from an "update" table while ignoring nulls, blanks, or empty fields - sql

I have a main table that I am trying to update from a table that only has fields populated that need to be updated in the main table, using a unique ID to ensure I am updating only matched records. Here is what the SQL string looks like for the query:
UPDATE [tblMain] INNER JOIN tblUpdate ON tblMain.UUID = tblUpdate.UUID
SET tblMain.contractName = tblUpdate.contractName
WHERE ((tblUpdate.contractName) IS NOT NULL);
The idea is to only pull the fields from the update table that actually have data, and ignore the fields that are either NULL, blank, or empty. To be clear, I want to include ALL records in the tbleUpdate, but only update with the fields that contain data. How can I do this?

If you want to UPDATE one table from another in MS Access, you should do this
UPDATE tblMain, tblUpdate
SET tblMain.contractName = tblUpdate.contractName
WHERE tblMain.UUID = tblUpdate.UUID
AND tblUpdate.contractName IS NOT NULL

Related

SQL update records with join table

Currently I need to move three columns from table A to table B. And I am using the update join table script to copy the existing data to the new columns. Afterwards the old column at table A will be drop.
Alter table NewB add columnA integer
Alter table NewB add columnB integer
Update NewB
Set NewB.columnA = OldA.columnA, NewB.columnB = OldA.columnB
From NewB
Join OldA on NewB.ID = OldA.ID
Alter table OldA drop column columnA
Alter table OldA drop column columnB
These script will add new columns and update the existing data from the old table to the newly created columns. Then remove the old columns.
But due to system structure, I will required to run SQL Script for more than one times to makes sure the database is up to date.
Although I did If (Columns Exist) Begin (Alter Add, Update, Alter Drop) End to ensure the existence of columns required. But when the script runs at the next time, it will hit error that says the columns was not found from the old table in the "update" query. Because the columns were dropped when the script run at the first time.
Is there other ways to solve?
you will not be able to update using join, But you can do like this :
Update NewB set NewB.columnA = (select OldA.columnA from OldA where NewB.ID = OldA.ID);
Update NewB set NewB.columnB = (select OldA.columnB from OldA where NewB.ID = OldA.ID);
I don't know which database you are using, in database there are some system tables, from where you can get whether the column does exist in table or not, like in oracle, All_TAB_COLUMNS contains the information of all the columns of tables, so you can hit that table like below :
select 1 from ALL_TAB_COLUMNS where TABLE_NAME='OldA' and COLUMN_NAME in ('columnA','columnB');
if resulting records are empty that means specified columns are not present in the table so you can skip your queries.
There must be something wrong with your is column exists check. I have similar DDL and DML operations many times. As you did not show how you are checking column existence I am not able to tell you what's wrong.
Anyway, you are adding a new column to a table. We can check if such column exists, if not - run the script, if yes- skip the script. And here is the check:
IF EXISTS(SELECT 1 FROM [sys].[columns] WHERE OBJECT_ID('[dbo].[NewB]') = [object_id] AND [name] = 'columnA')
BEGIN
BEGIN TRANSACTION;
....
COMMIT TRANSACTION;
END;

SQL update set table if value in table A is equals to value in table B

this query is working fine.
UPDATE data
SET unit_id='a3110a89'
WHERE unit_id='7d18289f';
Now, I need to run this query over 30 times
so I made csv file import it to the DB with this command:
COPY mytable FROM 'D:/test.csv' WITH CSV HEADER DELIMITER AS ','
Now I have table called my table with 2 columns OLD and NEW
i want to search the table "data" in column unit_id anywhere there if the value equals to the value in table "mytable.old" replace it with the value "mytable.new" on the same row.
I tried to run this query but I get an error:
UPDATE data
SET unit_id=(SELECT mytable."old" FROM public.mytable)
WHERE unit_id=(SELECT mytable."new" FROM public.mytable)
error:
more than one row returned by a subquery used as an expression
I think i'm just trying to do it in the wrong way...
thx for the help!
by the way Im using PostgreSQL
Your subqueries need to be correlated to the outer update:
UPDATE data
SET unit_id = (SELECT mytable."new" FROM public.mytable where data.old = mytable.old)
WHERE unit_id in (SELECT mytable."old" FROM public.mytable);
That is, set the unit_id to the "new" value, when you find the "old" value in the table.
Can you try like this,
UPDATE data A
SET A.unit_id=B.old
FROM (SELECT mytable."old",mytable."new" FROM public.mytable) B
WHERE A.unit_id=B.new
UPDATE data A
SET unit_id = B."old"
FROM public.mytable B
WHERE A.unit_id = B."new"
;
BTW: it looks like you also have old and new swapped in your question. Do you really want A's value to be set to B's old field?

How to Update a Single record despite multiple Occurances of the same ID Number?

I have a table that looks like the below table:
Every time the user loan a book a new record is inserted.
The data in this table is derived or taken from another table which has no dates.
I need to update this tables based on the records in the other table: Meaning I only need to update this table based on what changes.
Example: Lets say the user return the book Starship Troopers and the book return is indicated to Yes.
How do I update just that column?
What I have tried:
I tried using the MERGE Statement but it works only with unique rows of data, meaning you get an error if the same ID appears more than once.
I also tried using a basic UPDATE Statement and a JOIN but that's not going well.
I am asking because I have ran out of ideas.
Thanks for reading
If you need to update BooksReturn in target table based on the same column in source table
UPDATE t
SET t.booksreturn = s.booksreturn
FROM target t JOIN source s
ON t.userid = s.userid
AND t.booksloaned = s.booksloaned
Here is SQLFiddle demo
You can do this by simple Update & Insert statement.....
Two table A & B
From B you want to insert data into A if not exists other wise Update that data....
,First Insert into temp table....
SELECT *
INTO #MYTEMP
FROM B
WHERE BOOKSLOANED NOT IN (SELECT BOOKSLOANED
FROM A)
,Second Check data and insert into A.
INSERT INTO A
SELECT *
FROM #MYTEMP
And at last write one simple update statement which update all data of A. If any change then it also reflect to that data otherwise data as it is.
You can also update from #MYTEMP table.

Updating Records in Table A based on Records in Table B

I have to write a statement which fills a table (customers) with synthetically generated values. There is an addtional constraint that I should only fill those attributes (columns) with a special property (i.e. formally do a projection on them and then operate on them exclusively). These properties are stored in a second table, attributes.
My first draft consists of the following two statements:
-- Get the attributes (columns) we are interested in only
SELECT attributeID from attributes
WHERE tableID = 'customers'
-- Iterate over each row of customers, filling only those attributes (columns)
-- obtained by the above SELECT statement
UPDATE customers
SET (use the records from above select statement...)
Now my problem is how to put them together. I know there is the possibility of appending a WHERE clause to the SET clause, but that would select rows, not columns, as I need. I also read about PIVOT, but so far only inside one single table, not two, as is the case here. I would be very thankful for any hint, since I have no idea how to do this.
is not it you're looking for?
SQL Update Multiple Fields FROM via a SELECT Statement
UPDATE
Table
SET
Table.col1 = other_table.col1,
Table.col2 = other_table.col2
FROM
Table
INNER JOIN
other_table
ON
Table.id = other_table.id
Standard SQL-92 requires a scalar subquery:
UPDATE customers
SET attributeID = (
SELECT A1.attributeID
FROM attributes AS A1
WHERE A1.tableID = 'customers'
);
However, UPDATE customers...WHERE A1.tableID = 'customers' "smells" like you may be mixing data with metadata.

How to merge existing row with new data in SQLite?

I have a database full of simple note data, with columns for title, due date, priority, and details. There is also a _id column PRIMARY KEY int.
Say I have a note in the table already with some data filled and the rest null. I also have a set of data that will fill all those fields.
Is there a way that I can only write data to the fields that are NULL?
I can't overwrite existing data, but I'd like to add data to NULL columns.
I know the rowId of the target row.
If my target row had rowId of 5, I could do something like this:
UPDATE SET duedate='some date', priority='2', details='some text' WHERE _id=5
But that would overwrite all the data in that row, and I don't want to lose any data that might be there. How can I change this statement to avoid writing to non-null fields?
Suppose you start with
CREATE TABLE "t" ("a" , "b" , "c" );
INSERT INTO "t" ("a", "c") VALUES (1, 3);
Then
update t set a = coalesce(a,9), b = coalesce(b,10), c = coalesce(c,11);
Will update only the null values, ie. only column B will be set to 10. A and C will be left alone because they contain values.
Coalesce means pick the first item in the list that is not null.
The UPDATE statement only changes the fields you specify in the SET clause. If there are fields whose value you want left unmodified, then simply don't specify those fields in the SET clause.
Put another way, UPDATE doesn't write to all fields in the table - just the fields you specify for the rows you select with the WHERE clause.
If you simply don't know if the existing data is NULL or not, you can set the values using IFNULL(CurrentValue, NewValueIfNull). E.g.
UPDATE SET due_date=IFNULL(due_date, "some date") ... etc..
This will merge your new values into the row where there NULL values, and leave non-NULL values as they were.
See SQL Lite, IFNULL
How about:
UPDATE SET duedate='some date' WHERE _id=5 and duedate is null;
UPDATE SET priority='2' WHERE _id=5 and priority is null;
UPDATE SET details='some text' WHERE _id=5 and priority is null;
If you use Mysql, you can lookup IF()-then you can create a one liner. I think you can do something with similar in Oracle with case...