Riyan
Riyan

Reputation: 117

Cannot create temporary table in view definition PostgreSQL

CREATE  VIEW  viewRebalancingLog AS


CREATE TEMP TABLE newSessionID
(
  ilog_id INT,vch_service_name VARCHAR(200), vch_service_id  VARCHAR(200),iuser_id INT,vch_session_id  VARCHAR(200),
  isequence_id INT,vch_message_type  VARCHAR(200),vch_message_sub_type  VARCHAR(200),vch_message  VARCHAR,
  dt_service_log_time TIMESTAMP,dt_inserted_date TIMESTAMP
)


 INSERT INTO newSessionID
      ("ilog_id", "vch_service_name", "vch_service_id"  , "iuser_id" , "vch_session_id"  , "isequence_id" ,
  "vch_message_type"  ,"vch_message_sub_type","vch_message","dt_service_log_time","dt_inserted_date"
)
SELECT
     "LOGS"."ilog_id", "LOGS"."vch_service_name","LOGS"."vch_service_id","LOGS"."iuser_id" ,"LOGS"."vch_session_id"  ,
  "LOGS"."isequence_id" ,"LOGS"."vch_message_type"  ,"LOGS"."vch_message_sub_type" ,"LOGS"."vch_message",
  "LOGS"."dt_service_log_time","LOGS"."dt_inserted_date"
  FROM services_logs_stg AS "LOGS"
   WHERE ("LOGS".dt_service_log_time AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York') :: DATE =
         (((NOW() -
           INTERVAL '2 day')  :: TIMESTAMP) AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York') :: DATE

Upvotes: 6

Views: 3692

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 176124

You can't create temp table inside VIEW. Check CREATE VIEW:

CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] [ RECURSIVE ] VIEW name [ ( column_name [, ...] ) ] [ WITH ( view_option_name [= view_option_value] [, ... ] ) ] AS query

Why not use simple CREATE VIEW ... AS SELECT:

CREATE  VIEW  viewRebalancingLog AS
SELECT
     "LOGS"."ilog_id", "LOGS"."vch_service_name","LOGS"."vch_service_id","LOGS"."iuser_id" ,"LOGS"."vch_session_id"  ,
  "LOGS"."isequence_id" ,"LOGS"."vch_message_type"  ,"LOGS"."vch_message_sub_type" ,"LOGS"."vch_message",
  "LOGS"."dt_service_log_time","LOGS"."dt_inserted_date"
  FROM services_logs_stg AS "LOGS"
   WHERE ("LOGS".dt_service_log_time AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York') :: DATE =
         (((NOW() -
           INTERVAL '2 day')  :: TIMESTAMP) AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York') :: DATE;

If you need some sort of intermediate steps consider using common table expressions.

EDIT:

No,this is not end of the Query that i have posted, i have more temp table and JOIN each other. my goal is: 1.create temp table1, 2.insert data in temp table1 than 3.create temp table 2 4.insert data in temp table 2 5.create temp table 3 6.insert data from temp1 join temp2 7. select * from temp3

You could simply use CTE as I proposed before:

WITH temp1 AS (
    SELECT  ...
    FROM ...
), temp2 AS (
    SELECT ...
    FROM ...
)
SELECT *
FROM temp1
JOIN temp2
  ON ...

Upvotes: 8

Related Questions