我有下面的代码,但在else部分中引发了语法错误。
INSERT INTO tbl1 ("Name")
values
((SELECT CASE
WHEN EXISTS(select "OccupationID" from "tbloccupations" where "Name" = '-')
THEN (select "OccupationID" from "tbloccupations" where "Name" = '-')
ELSE (INSERT INTO "tbloccupations" ("Name") VALUES ('-') RETURNING "OccupationID")
END)
);
这应该运行的实际查询感谢您的帮助:
ALTER TABLE tblcustomers DISABLE TRIGGER ALL;
INSERT INTO public.tblcustomers
("CustomerID","Surname","OtherNames","Sex","DateOfBirth","OccupationID","Residence","PostalAddress","TownID",
"NextOfKin","NextOfKinRelationship","NextOfKinContact","EmailAddress","DateRegistered","IDTypeID","IDNumber",
"OutPatientNo","InPatientNo","Telephone1","Telephone2","PostalCode","Note","ReferenceNo","NationalityID",
"RegisteredAtCompanyBranchID","RegisteredBySysUID","IsActive")
VALUES('-2','-','-','0','12/12/2012 12:00:00 AM',
(SELECT CASE WHEN EXISTS(select "OccupationID" from "tbloccupations" where "Name" = '-')
THEN(select "OccupationID" from "tbloccupations" where "Name" = '-')
ELSE(INSERT INTO "tbloccupations" ("Name") VALUES ('-') RETURNING "OccupationID") END),
'-','-',
(SELECT CASE WHEN EXISTS(select "TownID" from "tbltowns" where "Name" = '-') THEN
(select "TownID" from "tbltowns" where "Name" = '-')
ELSE(INSERT INTO "tbltowns" ("Name") VALUES ('-') RETURNING "TownID") END),
'-','-','-','-','9/10/2014 12:00:00 AM','0','-','0','0','-','-','-','-','-','0','0','0','1')
ON CONFLICT DO NOTHING;ALTER TABLE tblcustomers ENABLE TRIGGER ALL;
答案 0 :(得分:1)
如果我正确理解了您的逻辑,则希望在名称为OccupationID
时插入-
,否则要插入-
:
INSERT INTO tbl1 (Name)
SELECT CASE WHEN Name = '-' THEN OccupationID ELSE '-' END
FROM tbloccupations
RETURNING OccupationID;
我不确定您目前是否可以在VALUES
子句中使用子查询,但是无论如何,您的问题更适合INSERT INTO ... SELECT
。
注意:如果OccupationID
列为数字,则必须使用OccupationID::text
之类的字符将其转换为文本,以使CASE
表达式起作用。>