我正在尝试动态计算表中保存的空值的数量。到目前为止,我有这个:
BEGIN
DECLARE STMT VARCHAR(2000);
FOR v AS CRS CURSOR FOR
SELECT NAME
FROM SESSION.TT1
DO
SET STMT = 'UPDATE SESSION.TT1 TT1
SET NULL_COUNT = (
SELECT COUNT(*) - COUNT('''||v.NAME||''') NULL_COUNT
FROM Table1
)
WHERE TT1.COLUMN_NAME = '''||v.NAME||'''';
EXECUTE IMMEDIATE STMT;
END FOR;
END
这很好用,并且确实用数据填充了临时表,但是它用相同的值更新每一行(这显然是错误的)。
我哪里出错了?
注意:
答案 0 :(得分:1)
您需要在列名两边加上双引号(或不加引号),否则您只是在计算文字值,而不是列...
DROP TABLE TABLE1@
CREATE TABLE TABLE1(C INT)@
INSERT INTO TABLE1 VALUES(NULL),( NULL)@
DECLARE GLOBAL TEMPORARY TABLE TT1(NAME VARCHAR(128), NULL_COUNT BIGINT)@
INSERT INTO SESSION.TT1 VALUES ('C',null)@
BEGIN
DECLARE STMT VARCHAR(2000);
FOR v AS CRS CURSOR FOR
SELECT NAME
FROM SESSION.TT1
DO
SET STMT = 'UPDATE SESSION.TT1 TT1
SET NULL_COUNT = (
SELECT COUNT(*) - COUNT("'||v.NAME||'") NULL_COUNT
FROM TABLE1
)
WHERE TT1.NAME = '''||v.NAME||'''';
EXECUTE IMMEDIATE STMT;
END FOR;
END
@
SELECT * FROM SESSION.TT1
@
NAME NULL_COUNT
---- ----------
C 2