我在oracle 11g中写了一个游标,如下所示:
DECLARE CURSOR QnA_cursor IS
SELECT activity_id, question, answer
FROM TABLE1
WHERE question != 'surveyText'
ORDER BY activity_id, question;
cur_count INT := 1;
que NVARCHAR2(10);
ans NVARCHAR2(10);
sqlCommand NVARCHAR2(500);
RowCountVar INT;
BEGIN
FOR QueAns
IN QnA_cursor
LOOP
IF cur_count = 4 THEN cur_count := 1; END IF; /* We have only 3 questions for each activity_id */
que := 'question' || cur_count; /* question1, question2, question3 */
ans := 'answer' || cur_count; /* answer1, answer2, answer3 */
sqlCommand := 'UPDATE TABLE2 SET '||que||' = :1, '||ans||' = :2 WHERE activity_id = :3';
EXECUTE IMMEDIATE sqlCommand USING QueAns.question, QueAns.answer, QueAns.activity_id;
cur_count := cur_count + 1;
END LOOP;
END;
这是TABLE1和TABLE2的架构:
Create table TABLE2(
ACTIVITY_ID NUMERIC(19,0),
QUESTION1 NVARCHAR2(2000),
ANSWER1 NVARCHAR2(2000),
QUESTION2 NVARCHAR2(2000),
ANSWER2 NVARCHAR2(2000),
QUESTION3 NVARCHAR2(2000),
ANSWER3 NVARCHAR2(2000)
)
Create table TABLE1(
ACTIVITY_ID NUMERIC(19,0),
QUESTION NVARCHAR2(2000),
ANSWER NVARCHAR2(2000)
)
当我尝试在sqldeveloper中编译它时,我在执行动态查询的行中遇到以下错误' EXECUTE IMMMEDIATE':
PLS-00382: expression is of wrong type
我玩过很多次,但无法弄清楚原因。表中的相应列的数据类型相同。你能告诉我一个什么问题吗?
答案 0 :(得分:5)
将sqlCommand的数据类型从NVARCHAR2更改为varchar2。执行立即预期varchar,varchar2或char。下面给出的代码应该有效
DECLARE
CURSOR qna_cursor IS
SELECT activity_id,
question,
answer
FROM table1
WHERE question != 'surveyText'
ORDER BY activity_id,
question;
cur_count INT := 1;
que VARCHAR2(10);
ans VARCHAR2(10);
sqlcommand VARCHAR2(500); --> Should be varchar, varchar2 or char
rowcountvar INT;
BEGIN
FOR queans IN qna_cursor LOOP
IF cur_count = 4 THEN
cur_count := 1;
END IF; /* We have only 3 questions for each activity_id */
que := 'question' || cur_count; /* question1, question2, question3 */
ans := 'answer' || cur_count; /* answer1, answer2, answer3 */
sqlcommand := 'UPDATE TABLE2 SET ' || que || ' = :1, ' || ans || ' = :2 WHERE activity_id = :3';
EXECUTE IMMEDIATE sqlcommand USING queans.question, queans.answer, queans.activity_id;
cur_count := cur_count + 1;
END LOOP;
END;
/