语法错误在或附近" CONSTRAINT" PostgreSQL的

时间:2016-06-28 12:26:19

标签: postgresql constraints create-table

我正在尝试创建一个新表,并在下面的语句中继续获得syntax error at or near "CONSTRAINT"。我已经确定在我声明的最后一列之后有一个,,它在CONSTRAINT行的正上方Tags。有谁知道为什么会这样?声明约束的所有在线示例似乎都涉及CREATE TABLE语句,而不是CREATE TABLE AS语句。那有关系吗?谢谢你的帮助!

顺便说一下,下面的约束行是从我创建的表中复制/粘贴的,它使用的是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";

1 个答案:

答案 0 :(得分: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作为撰稿人。