GBQ - Execute INSERT query ONLY if SELECT query returns results - sql

This question has been asked before in many forms. But none of the solutions proposed worked for my case.
I am using GBQ.
I have this table:
Hour Orders
2022-01-12T00:00:00 12
2022-01-12T01:00:00 8
2022-01-12T02:00:00 9
I want to create a query to insert data into this table automatically per hour, under these conditions:
If the "most recent hour" that I want to insert already exists, I do not want to insert it twice.
I tried the following SQL query :
IF EXISTS (SELECT 1 FROM `Table` WHERE Hour = var_most_recent_hour)
UPDATE `Table` SET Orders = var_most_recent_orders WHERE Hour = var_most_recent_hour
ELSE
INSERT INTO `Table` (Hour, Orders) VALUES (var_most_recent_hour, var_most_recent_orders)
This syntax is returning an error in GBQ, although the SQL syntax is usually accepted.
Is there a way to do this?
My priority is to insert without duplicates.
I don't care about the UPDATE part in my query.
Ideally I want something like (I know this syntax does not exist):
IF NOT EXISTS (SELECT 1 FROM `Table` WHERE Hour = var_most_recent_hour)
INSERT INTO `Table` (Hour, Orders) VALUES (var_most_recent_hour, var_most_recent_orders)
Thank you

Try Sample code below
declare most_rcnt_hour time;
INSERT INTO dataset.targettable(...
SELECT *
FROM dataset.targettable T
JOIN (SELECT most_rcnt_hour AS most_rcnt_hour) as S
ON T.rcnt_hour <> S.most_rcnt_hour
Note that IF in BQ works differently. IF

Related

Insert in to a table which is filtered by a specific account number

I have tried many times but i could not find the proper answer again i am asking same questing,
1 query
(select * From acct_db2016.dbo.acct_tran where trc_acno='12008001')if i search like this i am getting 10 rows,
2 query
(select * From acct_db.dbo.acct_tran where trc_acno='12008001')i am getting 4 rows
so i want to insert to 1st query data base to 2nd query data base
so the answer rows will be 14
If you're inserting new values into the table, then you will use:
INSERT INTO ...
VALUES/SELECT...
If you're modifying data that already exists in the table, you will use:
UPDATE [Table]
SET [column] = [column]
WHERE condition

SQL - UPDATE Commands fails when using LIKE

I'm performing a bulk update on a column within a table. I need to change the current date from NULL to a past date.. Which I know works fine when performning against a single account. But when using a WILDCARD, this seems to fail.
Any ideas what my issue is, can I not use LIKE in subquery..
SET message.archived_at = (SELECT TO_CHAR(systimestamp-31, 'DD-MON-YY HH.MI.SS')
FROM dual)
WHERE EXISTS = (SELECT entity_id FROM user_info
WHERE UPPER(user_info.directory_auth_id) like 'USER%')
I have 10,000 records that I need to update..
I've changed to
UPDATE message
SET message.archived_at = (SELECT TO_CHAR(systimestamp-31, 'DD-MON-YY HH.MI.SS')
FROM dual)
WHERE EXISTS (SELECT entity_id FROM user_info
WHERE UPPER(directory_auth_id) like 'JLOADUSER1001%')
the SELECT query in the WHERE EXISTS section, when run by itself returns 10 users ID.. But when the whole query is run, this updates 1.8 million rows.. expected result is ~1500 rows..
LIKE clauses are allowed in Oracle subqueries and UPDATE statements. The line that seems erroneous is:
WHERE EXISTS = (SELECT entity_id FROM user_info
Use:
WHERE EXISTS (SELECT entity_id FROM user_info
instead

sql insert using select, case and subquery inside

select * into #transacTbl from tmpTrans
insert
select
(case when tmpT.TranStatus = 10
then(
select ID, 'Returned')
else(
select ID, 'GoodSale')
end)
from
(
select * from MainTransacSource
) as tmpT
I want to be able to insert the details of a transaction into a different table with a label if it is a returned or good sale/transaction. I did this to avoid the cursor so please avoid giving a solution using a cursor.
I know the code looks good but what I'm experiencing is that, the case statement only returns one value via subquery.
This is a simplified version of the code; I have at least 6 types of cases and should be able to insert by ROW. I hate to think that I have to repeat each case per column because the actual number of columns is about 38.
You may suggest another work-around if this doesn't fit the logic. Of course, without a cursor.
Without access to your tables and not knowing more about what precisely you want to acheive, try something like this:
select * into #transacTbl from tmpTrans
insert
select tmpT.ID,
(case when tmpT.TranStatus = 10
then 'Returned'
else 'GoodSale'
end)
from
(select * from MainTransacSource) as tmpT <OR simply MainTransacSource tmpT (maybe)>
Cheers.

SQL Insert/Update Issue

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.

Calling insert once a day

I'm looking to insert data into the database only once per day. The problem is that I want the sql query to check this (as the code is untouchable)
Currently any time anyone goes to a certain web page it calls the spInsertRate procedure.
INSERT INTO dbo.LU_ExchangeRates
(exch_Date,exch_Currency,exch_Rate)
VALUES(#exchDATE,#exchCurrency,#exchRate)
I'm guessing I have to do a select statement first, and if the select statements does not return a row, that means to run the insert statement. I just can't figure out how to code for this.
if you must do it as single SQL this will work
INSERT INTO dbo.LU_ExchangeRates
(exch_Date,exch_Currency,exch_Rate)
SELECT
#exchDATE,#exchCurrency,#exchRate
WHERE
NOT EXISTS (
SELECT * from dbo.LU_ExchangeRates
WHERE
exch_Date = #exchDATE and exch_Currency = #exchCurrency)
but its more common to see
IF NOT EXISTS (
SELECT * from dbo.LU_ExchangeRates
WHERE
exch_Date = #exchDATE and exch_Currency = #exchCurrency)
INSERT INTO dbo.LU_ExchangeRates
(exch_Date,exch_Currency,exch_Rate)
VALUES
#exchDATE,#exchCurrency,#exchRate
I'd put a unique constraint on the exch_Date column, then have spInsertRate run the insert and catch the exception if it fails.
IF NOT EXISTS (SELECT * FROM dbo.LU_ExchangeRates WHERE exch_Date = #exchDATE)
BEGIN
INSERT INTO dbo.LU_ExchangeRates (exch_Date,exch_Currency,exch_Rate) VALUES(#exchDATE,#exchCurrency,#exchRate)
END
You can define a composite unique index with the IGNORE_DUP_ROWS option (or what's its name), and then any failed inserts will be silently discarded.
This can be done on Sybase ASE, maybe not on MS SQL server.
I would do a single query that does its insert if it doesn't find today's date in the table. That way you don't have a race between the select an the insert. Maybe
INSERT INTO dbo.LU_ExchangeRates (...)
SELECT #exchDate, ...
WHERE NOT EXISTS (SELECT *
FROM dbo.LU_ExchangeRates
WHERE exch_date >= #exchDate
AND exch_Currency != #exchCurrency)