如何在 SQL DB2 合并语句中使用 AND & OR 条件
How to have AND & OR condition in SQL Merge statement for DB2
我有一个合并语句,当我不必考虑空值时它可以工作:
这行得通:
MERGE INTO LTABLE L
USING (SELECT 1392 UCL_USER_ID,11 REGISTER_ID ,5 REGION_ID FROM DUAL ) B
ON ( L.UCL_USER_ID = B.UCL_USER_ID
AND L.REGISTER_ID = B.REGISTER_ID
AND (L.REGION_ID = B.REGION_ID)
)
WHEN NOT MATCHED
THEN
INSERT (
L.LTABLE_ID
,L.UCL_USER_ID
,L.REGISTER_ID
,L.REGION_ID
)
VALUES (
SEQ_LTABLE_ID.NEXTVAL
,1392
,11
,5);
当我必须考虑 REGION_ID 的空值时,下面的工作:
MERGE INTO LTABLE L
USING (SELECT 1392 UCL_USER_ID,11 REGISTER_ID ,NULL REGION_ID FROM DUAL ) B
ON ( L.UCL_USER_ID = B.UCL_USER_ID
AND L.REGISTER_ID = B.REGISTER_ID
AND (L.REGION_ID IS NULL AND B.REGION_ID IS NULL)
)
WHEN NOT MATCHED
THEN
INSERT (
L.LTABLE_ID
,L.UCL_USER_ID
,L.REGISTER_ID
,L.REGION_ID
)
VALUES (
SEQ_LTABLE_ID.NEXTVAL
,1392
,11
,NULL);
问题是当这两个条件可以为 null 或某个数值时,我如何将这两个条件结合起来。我尝试了以下但 sql 开发人员给出了查询不正确的错误。
AND ((L.REGION_ID = B.REGION_ID) OR (L.REGION_ID IS NULL AND B.REGION_ID IS NULL))
错误:
SQL Error: DB2 SQL Error: SQLCODE=-418, SQLSTATE=42610, SQLERRMC=FCS already resolved to different type, DRIVER=4.17.29
这只是一个猜测,但问题可能出在 NULL
的默认类型上。也许演员可以解决问题:
MERGE INTO LTABLE L
USING (SELECT 1392 UCL_USER_ID, 11 as REGISTER_ID,
CAST(NULL as VARCHAR(255)) as REGION_ID
FROM DUAL ) B
ON ( L.UCL_USER_ID = B.UCL_USER_ID
AND L.REGISTER_ID = B.REGISTER_ID
AND (L.REGION_ID IS NULL AND B.REGION_ID IS NULL)
)
或者 REGION_ID
.
的任何合适的类型
我有一个合并语句,当我不必考虑空值时它可以工作:
这行得通:
MERGE INTO LTABLE L
USING (SELECT 1392 UCL_USER_ID,11 REGISTER_ID ,5 REGION_ID FROM DUAL ) B
ON ( L.UCL_USER_ID = B.UCL_USER_ID
AND L.REGISTER_ID = B.REGISTER_ID
AND (L.REGION_ID = B.REGION_ID)
)
WHEN NOT MATCHED
THEN
INSERT (
L.LTABLE_ID
,L.UCL_USER_ID
,L.REGISTER_ID
,L.REGION_ID
)
VALUES (
SEQ_LTABLE_ID.NEXTVAL
,1392
,11
,5);
当我必须考虑 REGION_ID 的空值时,下面的工作:
MERGE INTO LTABLE L
USING (SELECT 1392 UCL_USER_ID,11 REGISTER_ID ,NULL REGION_ID FROM DUAL ) B
ON ( L.UCL_USER_ID = B.UCL_USER_ID
AND L.REGISTER_ID = B.REGISTER_ID
AND (L.REGION_ID IS NULL AND B.REGION_ID IS NULL)
)
WHEN NOT MATCHED
THEN
INSERT (
L.LTABLE_ID
,L.UCL_USER_ID
,L.REGISTER_ID
,L.REGION_ID
)
VALUES (
SEQ_LTABLE_ID.NEXTVAL
,1392
,11
,NULL);
问题是当这两个条件可以为 null 或某个数值时,我如何将这两个条件结合起来。我尝试了以下但 sql 开发人员给出了查询不正确的错误。
AND ((L.REGION_ID = B.REGION_ID) OR (L.REGION_ID IS NULL AND B.REGION_ID IS NULL))
错误:
SQL Error: DB2 SQL Error: SQLCODE=-418, SQLSTATE=42610, SQLERRMC=FCS already resolved to different type, DRIVER=4.17.29
这只是一个猜测,但问题可能出在 NULL
的默认类型上。也许演员可以解决问题:
MERGE INTO LTABLE L
USING (SELECT 1392 UCL_USER_ID, 11 as REGISTER_ID,
CAST(NULL as VARCHAR(255)) as REGION_ID
FROM DUAL ) B
ON ( L.UCL_USER_ID = B.UCL_USER_ID
AND L.REGISTER_ID = B.REGISTER_ID
AND (L.REGION_ID IS NULL AND B.REGION_ID IS NULL)
)
或者 REGION_ID
.