2016-06-28 282 views
2

我試圖創建一個新表,並在下面的語句中繼續獲取syntax error at or near "CONSTRAINT"。我已經確認在我宣佈的最後一列之後有一個,,它是CONSTRAINT行右上方的Tags。有誰知道爲什麼會發生這種情況?所有在線聲明約束的例子似乎涉及CREATE TABLE語句,而不是CREATE TABLE AS語句。這很重要嗎?謝謝你的幫助!在「CONSTRAINT」處或附近的語法錯誤PostgreSQL

順便說一下,下面的約束線是從我創建的表中複製/粘貼的,它使用了CREATE TABLE語句,而不是CREATE TABLE AS語句,這就是爲什麼我詢問約束是否不起作用CREATE TABLE AS語句。

CREATE TABLE "2017Projects" AS 
SELECT 
    "STAGING_PROJECTS"."_PROJECT_NUMBER", 
    "STAGING_PROJECTS"."_PROJECT_DESCRIPTION", 
    "STAGING_PROJECTS"."_PROJECT_STATUS", 
    "STAGING_PROJECTS"."_TEMPLATE_FLAG", 
    "STAGING_PROJECTS"."_PROJECT_START_DATE", 
    "STAGING_PROJECTS"."_PROJECT_COMPLETION_DATE", 
    "STAGING_PROJECTS"."_COMPANY", 
    "STAGING_PROJECTS"."_LOCATION_NUMBER", 
    "STAGING_TASKS"."_PARENT_TASK_NUMBER", 
    "STAGING_TASKS"."_PARENT_TASK_DESCRIPTION", 
    "STAGING_TASKS"."_TASK_NUMBER", 
    "STAGING_TASKS"."_TASK_DESCRIPTION", 
    "STAGING_TASKS"."_TASK_START_DATE", 
    "STAGING_TASKS"."_TASK_COMPLETION_DATE", 
    "STAGING_TASKS"."_EBS_ACCOUNT", 
    "STAGING_TASKS"."_FUSION_ACCOUNT", 
    CASE 
     WHEN left("STAGING_PROJECTS"."_PROJECT_NUMBER",2) = 'C0' THEN 
      '('||"STAGING_PROJECTS"."_PROJECT_NUMBER"||') '||"STAGING_PROJECTS"."_PROJECT_DESCRIPTION" 
     ELSE 
      "STAGING_PROJECTS"."_PROJECT_DESCRIPTION" 
    END AS "Project", 
    '('||"STAGING_TASKS"."_TASK_NUMBER"||') '||"STAGING_TASKS"."_TASK_DESCRIPTION" AS "Task", 
    NULL AS "Investment_Priority", 
    NULL AS "Class", 
    NULL AS "Tags", 

    --ERROR ON NEXT LINE HERE!!! 
    CONSTRAINT "2017Projects_pk" PRIMARY KEY ("_PROJECT_NUMBER", "_TASK_NUMBER") 
FROM 
    "STAGING_PROJECTS"; 

回答

2

你需要使用第二語句添加約束:

CREATE TABLE "2017Projects" AS 
SELECT 
    "STAGING_PROJECTS"."_PROJECT_NUMBER", 
    ..., 
    NULL AS "Tags" 
FROM 
    "STAGING_PROJECTS"; 

ALTER TABLE "2017Projects" ADD CONSTRAINT "2017Projects_pk" 
    PRIMARY KEY ("_PROJECT_NUMBER", "_TASK_NUMBER") 

CREATE TABLEALTER TABLE報表應在一個事務中運行。

請通過this great Stack DBA article查看,並以@a_horse_with_no_name作爲貢獻者。

+1

僅供參考:https://www.postgresql.org/docs/9.5/static/sql-createtableas.html。 'create table as select'語法中沒有'constraint'部分。 –

+0

@RadekPostołowicz對不起,完全錯過了,由於某種原因。我搜索了「CREATE TABLE AS」,出於某種原因只看到了「CREATE TABLE」文檔,其中顯示了「約束」部分。 – christopheralan88

+1

@TimBiegeleisen謝謝,我想我可以做到這一點,但希望有一種方法可以在CREATE TABLE AS語句中完成。謝謝你的幫助! – christopheralan88

相關問題