我有以下数据结构...
CREATE TABLE MAIN.ADDRESS(
ID UUID PRIMARY KEY DEFAULT GEN_RANDOM_UUID() NOT NULL,
ADDRESS_LINE1 VARCHAR(100) NOT NULL,
ADDRESS_LINE2 VARCHAR(100),
CITY VARCHAR(50) NOT NULL,
STATE VARCHAR(2) NOT NULL,
ZIP VARCHAR(5) NOT NULL
);
CREATE TABLE MAIN.PERSON(
ID UUID PRIMARY KEY DEFAULT GEN_RANDOM_UUID(),
NAME VARCHAR(100) NOT NULL,
PHONE VARCHAR(13) NOT NULL,
EMAIL VARCHAR(100) NOT NULL,
ADDRESS_ID UUID NOT NULL REFERENCES MAIN.ADDRESS(ID),
);
CREATE TABLE MAIN.STORE(
ID UUID PRIMARY KEY DEFAULT GEN_RANDOM_UUID(),
NAME VARCHAR(100) NOT NULL,
PHONE VARCHAR(13) NOT NULL,
EMAIL VARCHAR(100) NOT NULL,
MANAGER_ID UUID NOT NULL REFERENCES MAIN.PERSON(ID),
ADDRESS_ID UUID REFERENCES MAIN.ADDRESS(ID)
);
现在我正在编写要插入的Query。第一步(添加商店管理器)适用于此查询...
WITH STORE_MANAGER_ADDRESS AS(
INSERT INTO MAIN.ADDRESS (ADDRESS_LINE1, CITY, STATE, ZIP)
VALUES ('4321 Hubbard Ave', 'Columbus', 'OH', '43217')
RETURNING ID
)
INSERT INTO MAIN.PERSON (NAME, PHONE, EMAIL, ADDRESS_ID)
SELECT 'John Doe','15555555555','jd@gmail.com', ID
FROM STORE_MANAGER_ADDRESS;
现在我想添加商店,所以我想也许是这样的......
DECLARE STORE_MANAGER_ADDRESS_ID UUID;
DECLARE STORE_ADDRESS_ID UUID;
DECLARE STORE_MANAGER_PERSON_ID UUID;
WITH STORE_MANAGER_ADDRESS AS(
INSERT INTO MAIN.ADDRESS (ADDRESS_LINE1, CITY, STATE, ZIP)
VALUES ('4321 Hubbard Ave', 'Columbus', 'OH', '43217')
RETURNING ID
)
SELECT ID FROM STORE_MANAGER_ADDRESS INTO STORE_MANAGER_ADDRESS_ID
WITH STORE_MANAGER AS(
INSERT INTO MAIN.PERSON (NAME, PHONE, EMAIL, ADDRESS_ID)
VALUES ('John Doe','15555555555','jd@gmail.com', STORE_MANAGER_ADDRESS_ID)
RETURNING ID
)
SELECT ID FROM STORE_MANAGER INTO STORE_MANAGER_PERSON_ID
WITH STORE_ADDRESS AS(
INSERT INTO MAIN.ADDRESS (ADDRESS_LINE1, CITY, STATE, ZIP)
VALUES ('1234 Main St', 'Columbus', 'OH', '43201')
RETURNING ID
)
SELECT ID FROM STORE_ADDRESS INTO STORE_ADDRESS_ID
INSERT INTO MAIN.STORE (NAME, PHONE, EMAIL, MANAGER_ID, ADDRESS_ID)
VALUES ('Store 1', '1231231234','a@b.com',STORE_MANAGER_PERSON_ID, STORE_ADDRESS_ID)
但它失败了,
syntax error at or near "UUID"
name: error
length: 93
severity: ERROR
code: 42601
position: 34
file: scan.l
line: 1087
routine: scanner_yyerror
我错过了什么?我该如何处理这样的事情?
答案 0 :(得分:2)
在一个查询中使用多个CTE:
WITH STORE_MANAGER_ADDRESS AS(
INSERT INTO MAIN.ADDRESS (ADDRESS_LINE1, CITY, STATE, ZIP)
VALUES ('4321 Hubbard Ave', 'Columbus', 'OH', '43217')
RETURNING ID AS STORE_MANAGER_ADDRESS_ID
),
STORE_MANAGER AS(
INSERT INTO MAIN.PERSON (NAME, PHONE, EMAIL, ADDRESS_ID)
SELECT 'John Doe',
'15555555555',
'jd@gmail.com',
STORE_MANAGER_ADDRESS_ID
FROM STORE_MANAGER_ADDRESS
RETURNING ID AS STORE_MANAGER_PERSON_ID
),
STORE_ADDRESS AS(
INSERT INTO MAIN.ADDRESS (ADDRESS_LINE1, CITY, STATE, ZIP)
VALUES ('1234 Main St', 'Columbus', 'OH', '43201')
RETURNING ID AS STORE_ADDRESS_ID
)
INSERT INTO MAIN.STORE (NAME, PHONE, EMAIL, MANAGER_ID, ADDRESS_ID)
SELECT 'Store 1',
'1231231234',
'a@b.com',
STORE_MANAGER.STORE_MANAGER_PERSON_ID,
STORE.ADDRESS.STORE_ADDRESS_ID
FROM STORE_MANAGER CROSS JOIN STORE ADDRESS;