I need to insert my values if only they are not presented in my table.
I wrote the function:
do
$$
declare
v_video_config_bundle_id bigint;
v_are_records_exist boolean;
begin
select id from config_bundle into v_video_config_bundle_id where code = 'video';
select count(id) > 0 from config_bundle into v_are_records_exist
where config_bundle_id = v_video_config_bundle_id
and preference = 'true' and amount = 0 and repeatability in (1,7,14,21,30,45) and format='day';
case
when (v_are_records_exist = false) then
insert into config_plan(config_bundle_id, amount, repeatability, format, payment_amount, preference_type, preference, trial, weight, status, is_default)
values (v_video_config_bundle_id, 0, 7, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false),
(v_video_config_bundle_id, 0, 14, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false),
(v_video_config_bundle_id, 0, 21, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false);
end;
end;
$$
But I still get an exception ERROR:
syntax error at or near ";"
Position: 1420
How to fix it?
Let SQL make all decisions; put all the determination logic into a single SQL statement. You can do this by converting the filtering logic into NOT EXISTS (SELECT ... structure. So something like:
insert into config_plan(config_bundle_id, amount, repeatability, format, payment_amount, preference_type, preference, trial, weight, status, is_default)
with new_config ( amount, repeatability, format, payment_amount, preference_type, preference, trial, weight, status, is_default) as
( values ( 0, 7, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false),
( 0, 14, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false),
( 0, 21, 'day', 0, 'personal', true, false, 2, 'ACTIVE', false)
)
select amount, repeatability, format, payment_amount, preference_type, preference, trial, weight, status, is_default
from new_config nc
where not exists ( select null
from config_plan cp
where (cp.preference, cp.amount , cp.repeatability ,cp.format) =
(nc.preference, nc.amount , nc.repeatability ,nc.format)
) ;
The above is not tested as you did not supply table description and sample data. However, see here for an example of the technique.
Related
I write a script to populate the database with values
Here is script row
INSERT INTO AbpUsers(EmailAddress, IsActive, IsDeleted, IsEmailConfirmed, Name, NormalizedEmailAddress, NormalizedUserName, Surname, UserName, AccessFailedCount, CreationTime, IsLockoutEnabled, IsPhoneNumberConfirmed, IsTwoFactorEnabled, Password, ShouldChangePasswordOnNextLogin)
VALUES
('faithsdispatching#yahoo.com', 1, 0, 1, '', UPPER (EmailAddress), '', '', '', 0, GETDATE(), 1, 1, 0, 'AQAAAAEAACcQAAAAEHriGqDq6AuQs33CBdyNdwuiZboPua2e6aXn9MjB/qzo44kbXAAsIY77BIfzKLJD1Q==', 0)
For NormalizedEmailAddress field I need to use EmailAddress to Upper
I try to use this UPPER (EmailAddress) but get this error
Line 1: Invalid column name 'EmailAddress'.
Any ideas on how I can use EmailAddress column?
I don't think what you're asking is possible at the moment.
As a quick workaround, you can insert your data into a temporary table, run the UPPER() command on the column to hit them all at once, and then SELECT INTO your desired table from your temporary table.
CREATE TABLE #TemporaryAbpUsers
(
EmailAddress...,
IsActive...
);
INSERT INTO #AbpUsers(EmailAddress, IsActive, IsDeleted, IsEmailConfirmed, Name, NormalizedEmailAddress, NormalizedUserName, Surname, UserName, AccessFailedCount, CreationTime, IsLockoutEnabled, IsPhoneNumberConfirmed, IsTwoFactorEnabled, Password, ShouldChangePasswordOnNextLogin)
VALUES
('faithsdispatching#yahoo.com', 1, 0, 1, '', 'faithsdispatching#yahoo.com', '', '', '', 0, GETDATE(), 1, 1, 0, 'AQAAAAEAACcQAAAAEHriGqDq6AuQs33CBdyNdwuiZboPua2e6aXn9MjB/qzo44kbXAAsIY77BIfzKLJD1Q==', 0);
UPDATE #TemporaryAbpUsers
SET NormalizedEmailAddress = UPPER(NormalizedEmailAddress);
SELECT * INTO AbpUsers
FROM #TemporaryAbpUsers;
Just change UPPER(EmailAddress) to UPPER ('faithsdispatching#yahoo.com')
INSERT INTO AbpUsers(EmailAddress, IsActive, IsDeleted, IsEmailConfirmed, Name, NormalizedEmailAddress, NormalizedUserName, Surname, UserName, AccessFailedCount, CreationTime, IsLockoutEnabled, IsPhoneNumberConfirmed, IsTwoFactorEnabled, Password, ShouldChangePasswordOnNextLogin)
VALUES
('faithsdispatching#yahoo.com', 1, 0, 1, '', UPPER ('faithsdispatching#yahoo.com'), '', '', '', 0, GETDATE(), 1, 1, 0, 'AQAAAAEAACcQAAAAEHriGqDq6AuQs33CBdyNdwuiZboPua2e6aXn9MjB/qzo44kbXAAsIY77BIfzKLJD1Q==', 0)
Use a variable for EmailAddress
DECLARE #EmailAddress NVARCHAR(100);
SET #EmailAddress = N'faithsdispatching#yahoo.com';
INSERT INTO AbpUsers(EmailAddress, IsActive, IsDeleted, IsEmailConfirmed, Name, NormalizedEmailAddress, NormalizedUserName, Surname, UserName, AccessFailedCount, CreationTime, IsLockoutEnabled, IsPhoneNumberConfirmed, IsTwoFactorEnabled, Password, ShouldChangePasswordOnNextLogin)
VALUES
(#EmailAddress, 1, 0, 1, '', UPPER(#EmailAddress), '', '', '', 0, GETDATE(), 1, 1, 0, 'AQAAAAEAACcQAAAAEHriGqDq6AuQs33CBdyNdwuiZboPua2e6aXn9MjB/qzo44kbXAAsIY77BIfzKLJD1Q==', 0);
For multiple inserts, then you could try an Insert-From-Select-From-Values.
INSERT INTO AbpUsers(EmailAddress, IsActive, IsDeleted, IsEmailConfirmed, Name, NormalizedEmailAddress, NormalizedUserName, Surname, UserName, AccessFailedCount, CreationTime, IsLockoutEnabled, IsPhoneNumberConfirmed, IsTwoFactorEnabled, Password, ShouldChangePasswordOnNextLogin)
SELECT EmailAddress, IsActive, IsDeleted, IsEmailConfirmed, Name,
UPPER(EmailAddress) AS NormalizedEmailAddress,
NormalizedUserName, Surname, UserName, AccessFailedCount, CreationTime, IsLockoutEnabled, IsPhoneNumberConfirmed, IsTwoFactorEnabled, Password, ShouldChangePasswordOnNextLogin
FROM (VALUES
('faithsdispatching#yahoo.com', 1, 0, 1, '', '', '', '', 0, GETDATE(), 1, 1, 0, 'AQAAAAEAACcQAAAAEHriGqDq6AuQs33CBdyNdwuiZboPua2e6aXn9MjB/qzo44kbXAAsIY77BIfzKLJD1Q==', 0)
, ('hellbendingsextra#funky.net', 1, 0, 1, '', '', '', '', 0, GETDATE(), 1, 1, 0, 'AQBBBBEAACcQAAAAEHriGqDq6AuQs33CBdyNdwuiZboPua2e6aXn9MjB/qzo44kbXAAsIY77BIfzKLJD2Q==', 0)
, ('yellowriverfishing#asia.org', 1, 0, 1, '', '', '', '', 0, GETDATE(), 1, 1, 0, 'AQCCCCEAACcQAAAAEHriGqDq6AuQs33CBdyNdwuiZboPua2e6aXn9MjB/qzo44kbXAAsIY77BIfzKLJD3Q==', 0)
) q(EmailAddress, IsActive, IsDeleted, IsEmailConfirmed, Name,
NormalizedUserName, Surname, UserName, AccessFailedCount, CreationTime, IsLockoutEnabled, IsPhoneNumberConfirmed, IsTwoFactorEnabled, Password, ShouldChangePasswordOnNextLogin)
I'm trying to Insert a double precision (ilosc_zlec) value into a table (M_ZAMWLASNEPOZ). First I use a select statement to get the value. After I run this part of code, I can see the correct value in the variable ( 39 ). Next I'm trying to insert the selected values in the table and most of them get inserted but field ILOSC with should become the value of ilosc_zlec shows NULL. Both ILOSC, ilosc_zlec are double precision variables.
for select t.strumet_katzw,a.kategoria,a.rok_zam,a.symbol_zam,a.indeks,a.nazwa,a.wyroznik,a.ilosc_zlec,a.lp_zam from m_zlecenia a
left join m_przewod_gl g
on g.kat_zlec= a.kategoria and g.rok_zlec= a.rok_zam and g.symb_zlec= a.symbol_zam and g.lp_zlec= a.lp_zam
left join m_przewod_op p
on p.kat_zlec= a.kategoria and p.rok_zlec= a.rok_zam and p.symb_zlec= a.symbol_zam and p.lp_zlec= a.lp_zam and p.nr_przew=g.nr_poz
left join m_kot t
on t.kod_oper= p.kod_oper
where a.wyroznik=:wyroznik and a.grupa_zl= 'KOP' and a.data_wykon is null and f_mid(p.kod_oper,1,4)='KOOD' and t.strumet_katzw is not null
into: strumet_katzw,:kategoria, :rok_zam, :symbol_zam, :indeks, :nazwa, :wyroznik, :ilosc_zlec,:lp_zam
do begin
select symbol_zam from m_zamwlasne where kategoria=:strumet_katzw and F_MID(symbol_zam,1,8) = (:symbol_zam||f_mid(:indeks,5,3)) into: symb_szukan_nagl ;
-- wypelniasz pozycje naglowka
INSERT INTO M_ZAMWLASNEPOZ (KATEGORIA, ROK_ZAM, SYMBOL_ZAM, LP_ZAM, INDEKS, ILOSC, TERMIN, CENA_ZAM, POBRANO_IL, ZREALIZOWANO, DATA_ZM, OPER, KOD_KONTRO, ZAKUP_DLA, NA_PRZEWOD, IL_PO_KONTROLI, JM, ILOSC_ZAK, REL_JM_ZAK, NR_ZAPOTRZEB, DATA_POTW, OPIS_POZ2, OPIS_POZ, KOOP_WYROB, KOOP_WYROB_ILOSC, POBRANO_KOOP, SKAD_KOPIA, TYP_INDEKSU, SUMA_DOST, DATA_REALIZ, LP_OFERTY, KONTO_KOSZT, NA_NADRZ, PRZEDMIOT, RABAT, PR_RABAT, CENA_JEDN, LP_OPER, ILOSC_REJOP_KOOP, ROZLICZONE)
VALUES (:strumet_katzw, :rok_zam, :symb_szukan_nagl, :lp_zam, :indeks, :ilosc_zlec, 'now', 0, 0, 'T', 'now', user, 'NN', NULL, NULL, 0, 'SZT', 0, 0, NULL, 'NOW', NULL, NULL, NULL, 0, 0, NULL, 'I', 0, 'NOW', 1, NULL, NULL, 'a', 0, 0, 0, NULL, NULL, NULL);
suspend;
end
In BigQuery, I have created a table with the below schema
id INTEGER NULLABLE
visits INTEGER NULLABLE
dimensions RECORD REPEATED
dimensions.value STRING
dimensions.key STRING
How to get sum(visits) by grouping device and state values?
Example data:
{"id": 1, visits: 100, "dimensions": [{"key":"device","value":"mobile"}, {"key":"state","value":"CA"}]}
{"id": 1, visits: 500, "dimensions": [{"key":"device","value":"desktop"}, {"key":"state","value":"CA"}]}
{"id": 1, visits: 200, "dimensions": [{"key":"device","value":"mobile"}, {"key":"state","value":"NY"}]}
{"id": 2, visits: 100, "dimensions": [{"key":"device","value":"mobile"}, {"key":"state","value":"CA"}]}
{"id": 2, visits: 500, "dimensions": [{"key":"device","value":"desktop"}, {"key":"state","value":"CA"}]}
{"id": 2, visits: 200, "dimensions": [{"key":"device","value":"mobile"}, {"key":"state","value":"NY"}]}
{"id": 2, visits: 780, "dimensions": [{"key":"device","value":"desktop"}, {"key":"state","value":"NY"}]}
I want id, device, state, sum(visits) in the output.
I could do a group by using a single dimension with below query but do not know how to do it for multiple dimensions.
SELECT id,d.value, sum(visits) FROM dataset.tabe_name,UNNEST(dimensions) as d where d.key = "device" group by id, d.value LIMIT 1000
And also is it possible to write a generic query when key values are not known in advance?
Below is for BigQuery Standard SQL
#standardSQL
SELECT
id,
(SELECT value FROM UNNEST(dimensions) WHERE key = "device") AS device,
(SELECT value FROM UNNEST(dimensions) WHERE key = "state") AS state,
SUM(visits) AS visits
FROM `dataset.tabe_name`
GROUP BY id, device, state
LIMIT 1000
You can try / play it with dummy data from your example as below
#standardSQL
WITH data AS (
SELECT 1 AS id, 100 AS visits, ARRAY<STRUCT<key STRING, value STRING>>[("device", "mobile"), ("state", "CA")] AS dimensions UNION ALL
SELECT 1, 100, [STRUCT<key STRING, value STRING>("device", "mobile"), ("state", "CA")] UNION ALL
SELECT 1, 500, [STRUCT<key STRING, value STRING>("device", "desktop"), ("state", "CA")] UNION ALL
SELECT 1, 200, [STRUCT<key STRING, value STRING>("device", "mobile"), ("state", "NY")] UNION ALL
SELECT 2, 100, [STRUCT<key STRING, value STRING>("device", "mobile"), ("state", "CA")] UNION ALL
SELECT 2, 500, [STRUCT<key STRING, value STRING>("device", "desktop"), ("state", "CA")] UNION ALL
SELECT 2, 200, [STRUCT<key STRING, value STRING>("device", "mobile"), ("state", "NY")] UNION ALL
SELECT 2, 780, [STRUCT<key STRING, value STRING>("device", "desktop"), ("state", "NY")]
)
SELECT
id,
(SELECT value FROM UNNEST(dimensions) WHERE key = "device") AS device,
(SELECT value FROM UNNEST(dimensions) WHERE key = "state") AS state,
SUM(visits) AS visits
FROM data
GROUP BY id, device, state
-- ORDER BY id, device, state
I'm trying to add 9500 or so records to a table from a different table, the problem is that the table I'm adding them to has an egregious amount of colums while the table I'm pulling from is pretty normalized so I'm not quite sure how to do the inner join on it, this is what I have so far:
INSERT INTO Products (Code, ManufacturerId, VendorId, IsActive, Name, NamePlural, ShortDescription, Description, UpSellMessage, Cost, Price, IsOnSale, SalePrice, IsShipable, ShipPrice, Weight, Length, Width, Height, HasCountryTax, HasStateTax, HasLocalTax, DateAdded, Keywords, Inventory_Tracked, DropShip, DownloadOneTime, DealTimeIsActive, MMIsActive, ProductType, RecurringSubscriptionPrice, PaymentPeriod, Term, BillingDelay, SaleType, BundleGroupID, ComputePrice, PriceUp, PriceChangedAmount, PriceChangedType, SwatchesPerRow, ChangeOnClick, ChangeOnMouseover, ShowCloseUpLink, LinkBigImage, SwatchAllignment, DescriptionAllignment, DetailLink)
FROM otherProducts table2
INNER JOIN table2
VALUES (table2.col1, 1, 1, 0, table2.col1, table2.col1, table2.col4, table2.col4, 'some message that does not matter', table2.col3, table2.col2, 0, '0', 1, '8', '3', '8', '8', '8', 1, 1, 1, '12/27/2013', ' ', 0, 0, 0, 0, 0, 0, 0, '0', 0, 0, 0, 0, 0, 1, '0', 0, 0, 0, 0, 0, 0, 0, 0, table2.col1+'.aspx');
I can see this is a giant mess, and it just gives me errors, can anyone help me with this?
You want the insert . . . select syntax:
INSERT INTO Products (Code, ManufacturerId, VendorId, IsActive, Name, NamePlural, ShortDescription, Description, UpSellMessage, Cost, Price, IsOnSale, SalePrice, IsShipable, ShipPrice, Weight, Length, Width, Height, HasCountryTax, HasStateTax, HasLocalTax, DateAdded, Keywords, Inventory_Tracked, DropShip, DownloadOneTime, DealTimeIsActive, MMIsActive, ProductType, RecurringSubscriptionPrice, PaymentPeriod, Term, BillingDelay, SaleType, BundleGroupID, ComputePrice, PriceUp, PriceChangedAmount, PriceChangedType, SwatchesPerRow, ChangeOnClick, ChangeOnMouseover, ShowCloseUpLink, LinkBigImage, SwatchAllignment, DescriptionAllignment, DetailLink)
select table2.col1, 1, 1, 0, table2.col1, table2.col1, table2.col4, table2.col4, 'some message that does not matter', table2.col3, table2.col2, 0, '0', 1, '8', '3', '8', '8', '8', 1, 1, 1, '12/27/2013', ' ', 0, 0, 0, 0, 0, 0, 0, '0', 0, 0, 0, 0, 0, 1, '0', 0, 0, 0, 0, 0, 0, 0, 0, table2.col1+'.aspx'
FROM otherProducts table2;
I don't think you need to do a join at all.
I have a query like this
SET QUOTED_IDENTIFIER OFF
SET DATEFORMAT 'mdy'
INSERT INTO TABLE1
(AccountID, TimeStamp, UserID, NodeID, Deleted, UserPriority, ParentRecordID, NodeLevel, Name, NodeClass, DeviceID, DeviceType, SubTypeLevel)
VALUES
(0, "10/03/2002 02:33:39", 0, 0, 0, 0, 0, 0,"XXXXXX",7000, 0, 0, 0`)
When I replace XXXXXX with منطقة تحكم بالبداية السريعة, the query after the string turns right to left like this
SET QUOTED_IDENTIFIER OFF
SET DATEFORMAT 'mdy'
INSERT INTO TABLE1
(AccountID, TimeStamp, UserID, NodeID, Deleted, UserPriority, ParentRecordID, NodeLevel, Name, NodeClass, DeviceID, DeviceType, SubTypeLevel)
VALUES
(0, "10/03/2002 02:33:39", 0, 0, 0, 0, 0, 0, "منطقة تحكم بالبداية السريعة", 7000, 0, 0, 0)
Please tell me how to overcome this.
I am using SQL server 2000 MSDE.
You can resolve this case by adding the letter N before each values entered (that need conversion)
For example:
INSERT INTO TABLE1(AccountID, TimeStamp, UserID, NodeID, Deleted, UserPriority,
ParentRecordID, NodeLevel, Name, NodeClass, DeviceID, DeviceType, SubTypeLevel)
VALUES
(0, "10/03/2002 02:33:39", 0, 0, 0, 0, 0, 0, "منطقة تحكم بالبداية السريعة"N, 7000, 0, 0, 0)
=>
Insert ... Into ... Values (id1,id2,..., N'Arabic word',N'Hebrew word',N'Chinese word');
This issue is solved when we add N before the nvarchar value.
SET QUOTED_IDENTIFIER OFF SET DATEFORMAT 'mdy' INSERT INTO ControlTreeEx (AccountID, TimeStamp, UserID, NodeID, Deleted, UserPriority, ParentRecordID, NodeLevel, Name, NodeClass, DeviceID, DeviceType, SubTypeLevel) VALUES (0, "10/03/2002 02:33:39", 0, 0, 0, 0, 0, 0, N'منطقة تحكم بالبداية', 7000, 0, 0, 0)