我有这个功能:
CREATE OR REPLACE FUNCTION CREATE_AIRSPACE_AVAILABILITY_RECORD
(cur_user VARCHAR, start_time VARCHAR, start_date VARCHAR, end_time VARCHAR, end_date VARCHAR, airspace_name VARCHAR)
RETURNS VOID AS '
DECLARE
c_user ALIAS for $1;
BEGIN
IF start_time IS NULL OR
start_date IS NULL OR
end_time IS NULL OR
end_date IS NULL THEN
INSERT INTO c_user.AIRSPACE_AVAILABILITY
(ASP_AIRSPACE_NM, ASA_TIME_ID, ASA_START_DT, ASA_END_DT)
SELECT airspace_name,
1,
ABP.ABP_START_DT,
ABP.ABP_STOP_DT
FROM ABP
WHERE EXISTS
(SELECT ASP.ASP_AIRSPACE_NM
FROM AIRSPACE ASP
WHERE ASP.ASP_AIRSPACE_NM = airspace_name);
ELSIF start_time IS NOT NULL AND
start_date IS NOT NULL AND
end_time IS NOT NULL AND
end_date IS NOT NULL THEN
INSERT INTO c_user.AIRSPACE_AVAILABILITY
(ASP_AIRSPACE_NM, ASA_TIME_ID, ASA_START_DT, ASA_END_DT)
SELECT airspace_name,
1,
TO_DATE(start_date||start_time,''YYMMDDHH24MI''),
TO_DATE(end_date||end_time,''YYMMDDHH24MI'')
FROM DUAL
WHERE EXISTS
(SELECT ASP.ASP_AIRSPACE_NM
FROM c_user.AIRSPACE ASP
WHERE ASP.ASP_AIRSPACE_NM = airspace_name);
END IF;
END ;
' LANGUAGE plpgsql;
我试着这样称呼它:
select * from CREATE_AIRSPACE_AVAILABILITY_RECORD('user1','','','','','');
我收到此错误:
ERROR: schema "c_user" does not exist
SQL state: 3F000
Context: SQL statement "INSERT INTO c_user.AIRSPACE_AVAILABILITY (ASP_AIRSPACE_NM, ASA_TIME_ID, ASA_START_DT, ASA_END_DT) SELECT $1 , 1, TO_DATE( $2 || $3 ,'YYMMDDHH24MI'), TO_DATE( $4 || $5 ,'YYMMDDHH24MI') FROM DUAL WHERE EXISTS (SELECT ASP.ASP_AIRSPACE_NM FROM c_user.AIRSPACE ASP WHERE ASP.ASP_AIRSPACE_NM = $1 )"
PL/pgSQL function "create_airspace_availability_record" line 23 at SQL statement
为什么c_user不会被我的param(user1)替换?
答案 0 :(得分:2)
当你写这样的东西时:
INSERT INTO c_user.AIRSPACE_AVAILABILITY
数据库假定'c_user'是名称空间,而不是变量。如果要在此类查询中使用c_user变量的值,则应使用execute statement:
execute 'INSERT INTO ' || c_user || '.AIRSPACE_AVAILABILITY';
答案 1 :(得分:0)
为什么c_user不会被我的param(user1)替换?
因为对象名称(元数据)不能用变量(数据)代替。
动态选择元数据通常不是最好的设计,但如果你需要使用它,你应该按照
的方式做一些事情。EXECUTE 'INSERT INTO ' || c_user || '.AIRSPACE_AVAILABILITY ' …
代替。
有关详细信息,请参阅here。