试图循环trhough列结果并插入DB2表?

时间:2017-04-24 14:45:55

标签: sql db2

我正在尝试在DB2中运行一个查询,该查询遍历从列中检索到的每个用户ID并将其插入到另一个表中 所有其他值都是唯一的。我在尝试插入时不断遇到问题。以下是错误代码。

有人可以帮助解决以下问题的错误。

FOR v_row AS  
SELECT Test.USR_ID FROM (SELECT usr_id 
FROM   dbo.usr_cust_xref ucx 
       JOIN dbo.custid_acct_xref cax 
         ON ucx.cust_id = cax.cust_id 
       JOIN dbo.acct_brdng_xref abx 
         ON cax.acct_nbr = abx.acct_nbr 
WHERE  abx.brdng_cd = 'PN' 
UNION 
SELECT uax.usr_id 
FROM   dbo.usr_acct_xref uax 
       JOIN dbo.acct_brdng_xref abx 
         ON uax.acct_nbr = abx.acct_nbr 
WHERE  abx.brdng_cd = 'PN' ) as Test


    DO           

EXECUTE IMMEDIATE 'insert into cxxcow.USERS_RESOURCES(RSRC_ID,USER_ID,UR_INSERT_FG,UR_INQUIRY_FG,UR_UPDTE_FG,UR_DELETE_FG,UR_BROWSE_FG,UR_OPENCLOSE_FG,
UR_UPT_DTE,UR_UPT_USR,UR_ACCESS_DTE,UR_ACCESS_USR,UR_CODE_WORD)
values('WEB-ICD-RPBD',' || v_row.usr_id || ','N','N','Y','N','N','O',CURRENT TIMESTAMP,'AMARENDAR',CURRENT TIMESTAMP,'AMARENDAR',' ')'



END FOR

- 错误:DB2 SQL错误:SQLCODE = -199,SQLSTATE = 42601,SQLERRMC = FOR;获取SQL SAVEPOINT HOLD FREE ASSOCIATE,DRIVER = 3.53.70 SQLState:42601 ErrorCode:-199

2 个答案:

答案 0 :(得分:0)

我推荐这种方法:

insert into table2
(field1, field2, etc)
select 
field1, field2, etc
from other tables

它在逻辑上等同且更简单。

答案 1 :(得分:0)

在您的情况下没有必要使用for循环,您可以直接执行它(在性能和可靠性方面更好)

insert into cxxcow.USERS_RESOURCES
(
RSRC_ID, USER_ID, UR_INSERT_FG, UR_INQUIRY_FG, UR_UPDTE_FG, UR_DELETE_FG, UR_BROWSE_FG,
UR_OPENCLOSE_FG, UR_UPT_DTE, UR_UPT_USR, UR_ACCESS_DTE, UR_ACCESS_USR, UR_CODE_WORD
)
SELECT 'WEB-ICD-RPBD', f0.USR_ID, 'N', 'N', 'Y', 'N', 'N',
'O', CURRENT TIMESTAMP, 'AMARENDAR', CURRENT TIMESTAMP, 'AMARENDAR', ' ' 
FROM 
(
SELECT usr_id 
FROM   dbo.usr_cust_xref ucx 
       JOIN dbo.custid_acct_xref cax 
         ON ucx.cust_id = cax.cust_id 
       JOIN dbo.acct_brdng_xref abx 
         ON cax.acct_nbr = abx.acct_nbr 
WHERE  abx.brdng_cd = 'PN' 
UNION 
SELECT uax.usr_id 
FROM   dbo.usr_acct_xref uax 
       JOIN dbo.acct_brdng_xref abx 
         ON uax.acct_nbr = abx.acct_nbr 
WHERE  abx.brdng_cd = 'PN' 
) as f0
where not exists 
(
    select * from cxxcow.USERS_RESOURCES f1
    where f0.USR_ID=f1.USER_ID

)