Postgresql - issue with INSERT INTO statement - sql

I have the following SQL:
drop table if exists core.fact_request_tickets;
create table core.fact_request_tickets (
id serial4 primary key,
ticket_no text not null,
title text not null,
sender_id int4 not null,
request text not null,
status_id int4 not null,
is_latest boolean null,
group_id int4 not null,
size_id int4 not null,
business_partner_team_project_id int4 not null,
"log" text not null,
rating_met_sla_id int4 not null,
rating_communicated_id int4 not null,
rating_timely_id int4 not null,
rating_self_sufficient_id int4 not null,
rating_complete_and_accurate_id int4 not null,
log_date timestamptz not null,
etl_batch_id int4 not null
);
with finalTable as (
select rts.ticket_no
, rts.title
, rts.sender_id
, rts.request
, rts.status_id
, (case when ls.last_log_date is null then false else true end) as is_latest
, rts.group_id
, rts.size_id
, rts.business_partner_team_project_id
, rts."log"
, rts.rating_met_sla_id
, rts.rating_communicated_id
, rts.rating_timely_id
, rts.rating_self_sufficient_id
, rts.rating_complete_and_accurate_id
, rts.log_date
, rts.etl_batch_id
from requestTickets rts
left join lastStatus ls on rts.log_date = ls.last_log_date
)
insert into core.fact_request_tickets
( ticket_no
, title
, sender_id
, request
, status_id
, is_latest
, group_id
, size_id
, business_partner_team_project_id
, "log"
, rating_met_sla_id
, rating_communicated_id
, rating_timely_id
, rating_self_sufficient_id
, rating_complete_and_accurate_id
, log_date
, etl_batch_id
)
select ticket_no
, title
, sender_id
, request
, status_id
, is_latest
, group_id
, size_id
, business_partner_team_project_id
, "log"
, rating_met_sla_id
, rating_communicated_id
, rating_timely_id
, rating_self_sufficient_id
, rating_complete_and_accurate_id
, log_date
, etl_batch_id
from finalTable
commit;
When I execute the following SQL:
select ticket_no
, title
, sender_id
, request
, status_id
, is_latest
, group_id
, size_id
, business_partner_team_project_id
, "log"
, rating_met_sla_id
, rating_communicated_id
, rating_timely_id
, rating_self_sufficient_id
, rating_complete_and_accurate_id
, log_date
, etl_batch_id
from finalTable
It returns data that I am expecting - specifically, there are records that have 'true' for the is_latest column. However, when I execute the entire script, and then I query the core.fact_request_tickets table, all the values for the is_latest column show up as 'false'. It seems the INSERT INTO statement is causing the data inserted into the core.fact_request_tickets table to show up incorrectly (there should be some records with a true value for is_latest, but instead all values return as false); but when I run the query against finalTable separately, it returns the data I am expecting.
I'm not sure why this is happening - any ideas?

It's got to be a syntax error in the script itself and unrelated to the "WITH AS" clause.
Semicolons are needed after the entire INSERT statement and before COMMIT;
COMMIT may not be supported in the batch environment you have (executing as OWNER context), rolling back any pending changes (so next select is looking at the old data).
I recommend sticking to a plain INSERT - SELECT statement (and testing that separately):
insert into core.fact_request_tickets
( ticket_no
, title
, sender_id
, request
, status_id
, is_latest
, group_id
, size_id
, business_partner_team_project_id
, "log"
, rating_met_sla_id
, rating_communicated_id
, rating_timely_id
, rating_self_sufficient_id
, rating_complete_and_accurate_id
, log_date
, etl_batch_id
) select rts.ticket_no
, rts.title
, rts.sender_id
, rts.request
, rts.status_id
, (case when ls.last_log_date is null then false else true end) as is_latest
, rts.group_id
, rts.size_id
, rts.business_partner_team_project_id
, rts."log"
, rts.rating_met_sla_id
, rts.rating_communicated_id
, rts.rating_timely_id
, rts.rating_self_sufficient_id
, rts.rating_complete_and_accurate_id
, rts.log_date
, rts.etl_batch_id
from requestTickets rts
left outer join lastStatus ls
on rts.log_date = ls.last_log_date;
Also, if this is a one-time query, consider using temporary tables. Which saves you overhead of logging and saving results permanently. A permission to create them may need to be granted to the batch account.

Related

SQL function not returning values in table but it will when ran separately

I have a function that for some reason is not bringing back data in the table, but if I cut down the code and test it by itself it works.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[ReportingCyclesForReporting]
(
#ReportingCycleId BIGINT
)
RETURNS #t TABLE
(
[ReportingCycleId] [bigint] NOT NULL,
[BusinessId] [bigint] NOT NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
[ScenarioId] [bigint] NULL,
[SourceReportingCycleId] [bigint] NULL,
[MjMEPerDay] [decimal](19, 4) NOT NULL,
[AssetAppreciation] [decimal](5, 2) NULL,
[LandAssetAppreciation] [decimal](5, 2) NULL,
[OffFarmAssetAppreciation] [decimal](5, 2) NULL,
[RolledOverDate] [datetime] NULL,
[Version] [int] NOT NULL,
[Archived] [bit] NOT NULL,
[Essential] [bit] NOT NULL,
[EssentialsLeasedLandValue] [decimal](19, 4) NOT NULL,
[EssentialsShareFarmedLandValue] [decimal](19, 4) NOT NULL,
[EssentialsWaterValue] [decimal](19, 4) NOT NULL,
[RolloverDataOverwrite] [bit] NULL
)
AS
BEGIN
DECLARE #businessId INT
DECLARE #scenarioId INT
DECLARE #essential BIT
-- Get businessid and scenario id for this reporting cycle
SELECT #businessId = BusinessId
, #scenarioId = ScenarioId
, #essential = Essential
FROM ReportingCycle
WHERE Id = #ReportingCycleId
AND Archived = 0
BEGIN
IF #scenarioId IS NOT NULL
begin
-- Scenario reporting cycle siblings of the given reporting cycle
INSERT INTO #t(
ReportingCycleId
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
)
SELECT rc.Id
, rc.BusinessId
, rc.StartDate
, rc.EndDate
, rc.ScenarioId
, rc.SourceReportingCycleId
, rc.MjMEPerDay
, rc.AssetAppreciation
, rc.LandAssetAppreciation
, rc.OffFarmAssetAppreciation
, rc.RolledOverDate
, rc.Version
, rc.Archived
, rc.Essential
, rc.EssentialsLeasedLandValue
, rc.EssentialsShareFarmedLandValue
, rc.EssentialsWaterValue
FROM ReportingCycle
INNER JOIN ReportingCycle rc ON rc.ScenarioId = ReportingCycle.ScenarioId AND rc.Archived = 0
WHERE ReportingCycle.Id = #ReportingCycleId
AND ReportingCycle.Archived = 0
ORDER BY rc.StartDate
end
ELSE IF EXISTS(SELECT * FROM FutureReportingCycles(#businessId, #essential) WHERE Id = #reportingCycleId)
begin
-- Future reporting cycles
INSERT INTO #t(
ReportingCycleId
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
)
SELECT Id
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
FROM FutureReportingCycles(#businessId, #essential)
END
ELSE IF EXISTS(SELECT * FROM HistoryReportingCycles(#businessId, #essential) WHERE Id = #reportingCycleId and ScenarioId is null)
BEGIN
-- History reporting cycles
INSERT INTO #t(
ReportingCycleId
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
)
SELECT Id
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
FROM HistoryReportingCycles(#businessId, #essential) where ScenarioId is null
END
ELSE
-- Now
BEGIN
INSERT INTO #t(
ReportingCycleId
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
)
SELECT Id
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
FROM ReportingCycle WHERE id = #ReportingCycleId and Archived = 0
END
END
RETURN
END
I will execute this to trigger it to test
select * from ReportingCyclesForReporting(14212)
This happens when it's a future reporting cycle. I will get an empty table returned. I've debugged this in Visual Studio and I can see that it goes into the correct branch with the correct values but the table returns nothing.
But if I run a cut down version of the script brings back the values.
DECLARE #t TABLE
(
[ReportingCycleId] [bigint] NOT NULL,
[BusinessId] [bigint] NOT NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
[ScenarioId] [bigint] NULL,
[SourceReportingCycleId] [bigint] NULL,
[MjMEPerDay] [decimal](19, 4) NOT NULL,
[AssetAppreciation] [decimal](5, 2) NULL,
[LandAssetAppreciation] [decimal](5, 2) NULL,
[OffFarmAssetAppreciation] [decimal](5, 2) NULL,
[RolledOverDate] [datetime] NULL,
[Version] [int] NOT NULL,
[Archived] [bit] NOT NULL,
[Essential] [bit] NOT NULL,
[EssentialsLeasedLandValue] [decimal](19, 4) NOT NULL,
[EssentialsShareFarmedLandValue] [decimal](19, 4) NOT NULL,
[EssentialsWaterValue] [decimal](19, 4) NOT NULL,
[RolloverDataOverwrite] [bit] NULL
)
INSERT INTO #t(
ReportingCycleId
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
)
SELECT Id
, BusinessId
, StartDate
, EndDate
, ScenarioId
, SourceReportingCycleId
, MjMEPerDay
, AssetAppreciation
, LandAssetAppreciation
, OffFarmAssetAppreciation
, RolledOverDate
, Version
, Archived
, Essential
, EssentialsLeasedLandValue
, EssentialsShareFarmedLandValue
, EssentialsWaterValue
FROM FutureReportingCycles(306, 0)
select * from #t
This will bring back the values
Here is a picture of it in debug mode showing it goes into that branch.
I would really appreciate some help with this.

How do I do create a table on SQL Developer by running a script on the SQL Worksheet?

enter code hereI'm trying to create a table by running an Script from the SQL Worksheet and ORA-00904 error appears.
I don't know maybe the script it's misspelled?
CREATE table IMAGEN (
[ID_ADM] [SMALLINT] NOT NULL ,
[ID_USUARIO] [varchar] (20) NOT NULL ,
[IMAGEN] [varbinary] (max),
[MINIATURA] [varbinary] (max),
[IMAGEN_ALT1] [varbinary] (max),
[IMAGEN_ALT2] [varbinary] (max),
[IMAGEN_ALT3] [varbinary] (max),
[ESTADO_REG] [varchar] (1) NULL ,
[FEC_ESTADO_REG] [datetime] NULL ,
[FEC_ING_REG] [datetime] NULL ,
[ID_USUARIO_ING_REG] [varchar] (20) NULL ,
[FEC_ULT_MODIF_REG] [datetime] NULL ,
[ID_USUARIO_ULT_MODIF_REG] [varchar] (20) NULL ,
[ID_FUNCION_ULT_MODIF_REG] [varchar] (16) NULL
) ON [PRIMARY]
GO
Here's one interpretation of this table in Oracle
create table IMAGEN (
ID_ADM smallint not null
, ID_USUARIO varchar2(20) not null
, IMAGEN blob
, MINIATURA blob
, IMAGEN_ALT1 blob
, IMAGEN_ALT2 blob
, IMAGEN_ALT3 blob
, ESTADO_REG varchar2(1) null
, FEC_ESTADO_REG date null
, FEC_ING_REG date null
, ID_USUARIO_ING_REG varchar2(20) null
, FEC_ULT_MODIF_REG date null
, ID_USUARIO_ULT_MODIF_REG varchar2(20) null
, ID_FUNCION_ULT_MODIF_REG varchar2(16) null
);
varchar2, never varchar in Oracle
date = datetime
blobs can store any amount of binary data

Insert from one table to another (different databases)

Auth2.dbo.Accounts : account_id, login_name , password , other columns...
Auth.dbo.Account : account_id , account , password , other columns...
I want to insert accounts(account_id,account,password) from "Auth.dbo.Account" to "Auth2.dbo.Accounts" (account_id,login_name , password) and giving other columns values that I want.
I was hoping that this could work , but once I wrote in SQL Management studio , I got an error syntax error near the " select account_id from Auth.dbo.account"
INSERT [dbo].[Accounts] ([account_id], [login_name], [password],
[referral_id], [referral_code], [pcbang], [block],
[withdraw_remain_time], [age], [auth_ok],
[last_login_server_idx], [event_code], [server_list_mask],
[result], [ip], [game_code], [gamecode], [login_event],
[email], [security_a_1], [security_a_2], [security_a_3],
[security_a_4], [security_q_1], [security_q_2], [security_q_3],
[security_q_4], [votepoints], [cash], [country])
VALUES (select account_id from auth.dbo.Account, N'Imad',
N'3cfbbd2ae3c3e416c6d00a5a12ee60e8', NULL, NULL,
0, 0, NULL, -1997, 1, NULL, NULL, NULL, NULL,
N'::1', NULL, NULL, NULL, N'imad.lekal#outlook.com',
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
0, 189, NULL)
Try with simple INSERT/SELECT. In this case account_id will be from auth.dbo.Account and all the other values will be constants.
INSERT Auth2.[dbo].[Accounts] ([account_id], [login_name], [password], [referral_id], [referral_code], [pcbang], [block], [withdraw_remain_time], [age], [auth_ok], [last_login_server_idx], [event_code], [server_list_mask], [result], [ip], [game_code], [gamecode], [login_event], [email], [security_a_1], [security_a_2], [security_a_3], [security_a_4], [security_q_1], [security_q_2], [security_q_3], [security_q_4], [votepoints], [cash], [country])
select account_id , N'Imad', N'3cfbbd2ae3c3e416c6d00a5a12ee60e8', NULL, NULL, 0, 0, NULL, -1997, 1, NULL, NULL, NULL, NULL, N'::1', NULL, NULL, NULL, N'imad.lekal#outlook.com', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 189, NULL from auth.dbo.Account;
Remove the VALUES (
When you INSERT using SELECT you should not use VALUES, since the values are coming from the SELECT
Also prefix the table names with the database names, assuming that Auth and Auth2 are 2 different databases.
Finally, your FROM is off.
Following should work.
INSERT Auth2.dbo.Accounts
(
[account_id]
, [login_name]
, [password]
, [referral_id]
, [referral_code]
, [pcbang]
, [block]
, [withdraw_remain_time]
, [age]
, [auth_ok]
, [last_login_server_idx]
, [event_code]
, [server_list_mask]
, [result]
, [ip]
, [game_code]
, [gamecode]
, [login_event]
, [email]
, [security_a_1]
, [security_a_2]
, [security_a_3]
, [security_a_4]
, [security_q_1]
, [security_q_2]
, [security_q_3]
, [security_q_4]
, [votepoints]
, [cash]
, [country]
)
SELECT
account_id
, N'Imad'
, N'3cfbbd2ae3c3e416c6d00a5a12ee60e8'
, NULL
, NULL
, 0
, 0
, NULL
, -1997
, 1
, NULL
, NULL
, NULL
, NULL
, N'::1'
, NULL
, NULL
, NULL
, N'imad.lekal#outlook.com'
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, 0
, 189
, NULL
FROM auth.dbo.Account
PRO TIP: Format your SQL properly bro, it helps to debug :).
hi i think this will help you first of all you create database link
CREATE DATABASE LINK your_db_link_name
CONNECT TO Schema_Name
IDENTIFIED BY <PWD>
USING 'Your Database Name';
next you need to make a query
INSERT [Accounts] ([account_id], [login_name], [password], [referral_id]
, [referral_code], [pcbang], [block], [withdraw_remain_time], [age], [
auth_ok], [last_login_server_idx], [event_code], [server_list_mask], [
result], [ip], [game_code], [gamecode], [login_event], [email], [
security_a_1], [security_a_2], [security_a_3], [security_a_4], [
security_q_1], [security_q_2], [security_q_3], [security_q_4], [
votepoints], [cash], [country])
VALUES (
select ac.account_id
from Your_DB_Link_Name#Account ac, N'Imad', N'3cfbbd2ae3c3e416c6d00a5a12ee60e8',
NULL, NULL, 0, 0, NULL, -1997, 1, NULL, NULL, NULL, NULL, N'::1', NULL,
NULL, NULL, N'imad.lekal#outlook.com', NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, 0, 189, NULL)
i think this will help you if you have any query then feel free

ORA-00922: missing or invalid option when using CREATE TABLE

I keep getting this error when I attempt to create tables. This is what I have so far:
CREATE TABLE Club
( Club_ID NUMBER(7) NOT NULL
, Club_Name VARCHAR2(35) NOT NULL
, Street_Addr VARCHAR2(40) NOT NULL
, City VARCHAR2(20) NOT NULL
, State CHAR(2) NOT NULL
, Zipcode NUMBER(7) NOT NULL
, Phone NUMBER(10) NOT NULL
, CONSTRAINT club_pk PRIMARY KEY (Club_ID)
)
CREATE TABLE Member
( Member_ID NUMBER(10) NOT NULL
, First_Name VARCHAR2(20) NOT NULL
, Last_Name VARCHAR2(30) NOT NULL
, Street_Addr VARCHAR2(40) NOT NULL
, City VARCHAR2(20) NOT NULL
, State CHAR(2) NOT NULL
, Zipcode NUMBER(7) NOT NULL
, Phone NUMBER(10) NOT NULL
, CONSTRAINT member_pk PRIMARY KEY (Member_ID)
) ;
I don't get any errors from each individually, but as soon as I put them together like this I run into problems. Adding a semicolon between the two CREATE TABLE sections causes a different error ("ORA-00911: invalid character"). What should I be doing differently?
Thanks!

SQL Product Table Creation - Incorrect Syntax

I am trying to create a products table running the following SQL query:
CREATE TABLE ‘products’ (
‘id’ INT NOT NULL AUTO_INCREMENT ,
‘name’ VARCHAR( 255 ) NOT NULL ,
‘shortdesc’ VARCHAR( 255 ) NOT NULL ,
‘longdesc’ TEXT NOT NULL ,
‘thumbnail’ VARCHAR( 255 ) NOT NULL ,
‘image’ VARCHAR( 255 ) NOT NULL ,
‘sizes’ ENUM( ‘s’, ‘m’, ‘l’, ‘xl’ ) NOT NULL ,
‘colors’ ENUM( ‘red’, ‘blue’, ‘green’, ‘brown’, ‘white’, ‘black’ ) NOT NULL ,
‘grouping’ VARCHAR( 16 ) NOT NULL ,
‘status’ ENUM( ‘active’, ‘inactive’ ) NOT NULL ,
‘category_id’ INT NOT NULL ,
‘featured’ ENUM (‘true’, ‘false’) NOT NULL,
‘price’ FLOAT( 4, 2 ) NOT NULL,
PRIMARY KEY ( ‘id’ )
) TYPE = MYISAM ;
However this error occurs:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '‘s’, ‘m’, ‘l’, ‘xl’ ) NOT NULL , ‘colors’ ENUM( ‘red’, ' at line 8
Which type should I use? I am following an example from a book.
After some playing I think I can say it is the ‘’ characters that are throwing it off. I ran this without issue:
CREATE TABLE `products2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`sizes` enum('s','m','l','xl') NOT NULL,
`colors` enum('red','blue','green','brown','white','black') NOT NULL,
`shortdesc` varchar(255) NOT NULL,
`longdesc` text NOT NULL,
`thumbnail` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`grouping` varchar(16) NOT NULL,
`status` enum('active','inactive') NOT NULL,
`category_id` int(11) NOT NULL,
`featured` enum('true','false') NOT NULL,
`price` float(4,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Using backticks and apostrophes instead of curly quotation marks seems to work for me
CREATE TABLE `products` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`shortdesc` VARCHAR( 255 ) NOT NULL ,
`longdesc` TEXT NOT NULL ,
`thumbnail` VARCHAR( 255 ) NOT NULL ,
`image` VARCHAR( 255 ) NOT NULL ,
`sizes` ENUM( 's', 'm', 'l', 'xl' ) NOT NULL ,
`colors` ENUM( 'red', 'blue', 'green', 'brown', 'white', 'black' ) NOT NULL ,
`grouping` VARCHAR( 16 ) NOT NULL ,
`status` ENUM( 'active', 'inactive' ) NOT NULL ,
`category_id` INT NOT NULL ,
`featured` ENUM ('true', 'false') NOT NULL,
`price` FLOAT( 4, 2 ) NOT NULL,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM ;