0

我想插入一个新数据,但是我想在查询中放置一个条件,如果有数据存在则不会插入,如果没有则可以插入。

INSERT INTO user_permission_index (guid, code, name,description, perm_type, time_create)   
VALUES 
(uuid_generate_v1(),'perm_trading_cashsale_by_branch','label_CanissueCashsaleByBranch','','acc_branch_index','0001-01-01') 
WHERE NOT EXISTS (SELECT * 
                  FROM user_permission_index 
                  WHERE code = 'perm_trading_cashsale_by_branch' 
                    AND name = 'label_CanissueCashsaleByBranch');

我在 WHERE NOT 处遇到语法错误。你们能帮帮我吗。谢谢。

4

2 回答 2

2

您需要使用 aSELECT而不是VALUES

INSERT INTO user_permission_index (guid, code, name,description, perm_type, time_create)   
select uuid_generate_v1(),
       'perm_trading_cashsale_by_branch',
       'label_CanissueCashsaleByBranch',
       '',
       'acc_branch_index',
       '0001-01-01' 
WHERE NOT EXISTS (SELECT * 
                  FROM user_permission_index 
                  WHERE code = 'perm_trading_cashsale_by_branch' 
                    AND name = 'label_CanissueCashsaleByBranch');

uuid_generate_v1()(由于该功能,我假设您是 PostgreSQL )

如果您正在使用“更新或插入”功能,您可能想查看以下内容:插入,在 PostgreSQL 中重复更新?

于 2013-09-25T09:05:23.360 回答
0

您需要将内部选择链接到外部插入语句

INSERT INTO user_permission_index upi (guid, code, name,description, perm_type, time_create) 
SELECT (uuid_generate_v1(),'perm_trading_cashsale_by_branch','label_CanissueCashsaleByBranch','','acc_branch_index','0001-01-01') 
WHERE NOT EXISTS (
SELECT * 
FROM user_permission_index 
WHERE code = 'perm_trading_cashsale_by_branch' 
  AND name = 'label_CanissueCashsaleByBranch'
      AND id = upi.id
);

但我觉得说得更好

INSERT INTO user_permission_index (guid, code, name,description, perm_type, time_create) 
SELECT (uuid_generate_v1(),'perm_trading_cashsale_by_branch','label_CanissueCashsaleByBranch','','acc_branch_index','0001-01-01') 
WHERE nvl(code, '') <> 'perm_trading_cashsale_by_branch'
   OR nvl(name, '') <> 'label_CanissueCashsaleByBranch';
于 2013-09-25T09:07:19.077 回答