Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql如果字段中为空,则整个sql为空_Postgresql - Fatal编程技术网

Postgresql如果字段中为空,则整个sql为空

Postgresql如果字段中为空,则整个sql为空,postgresql,Postgresql,我使用此sql执行sql: v_sql4 :=' INSERT INTO public.rebatesys(head,contract_no,history_no,f_sin,line_no,s_line_no,departmentcd,catagorycd,jan,seriescd,f_exclude, f_del,ins_date,ins_time,ins_user_id,ins_func_id,ins_ope_id,upd_date,upd_time,upd_use

我使用此sql执行sql:

    v_sql4 :='
    INSERT INTO public.rebatesys(head,contract_no,history_no,f_sin,line_no,s_line_no,departmentcd,catagorycd,jan,seriescd,f_exclude,     f_del,ins_date,ins_time,ins_user_id,ins_func_id,ins_ope_id,upd_date,upd_time,upd_user_id,upd_func_id,upd_ope_id)                                   
     VALUES (0, '''||v_contract_no||''', '||v_history_no||',1, '||v_line_no||', '||v_down_s_line_no||', '||coalesce(v_deptCD,null)||', '||0||', '''||v_singleJan||''','''||0||''','||v_fExclude||',
    0, current_date, current_time, '||v_ins_user_id||', 0, 0,
    current_date,current_time,'||v_upd_user_id||',0, 0);';
RAISE NOTICE 'v_sql4 IS : %', v_sql4;
    EXECUTE v_sql4;
但是当字段“v_deptCD”为空时,整个sql为空,即使我使用了
coalesce
,我仍然无法进行id,输出为:

NOTICE:  v_sql4 IS : <NULL>
注意:v_sql4是:

如何修复它?

v_deptCD
为空时,您希望用字符串
'null'
替换它,而不是关键字

', '||coalesce(v_deptCD,'null')||', '
你可以用这个

case when v_deptCD notnull then v_deptCD else null end
或者将其用于sql内部的字符串浓缩

concat(field1, ', ', field2)

JGH解决方案的另一种方法是使用函数,它可以忽略空值,但如果在格式字符串中使用
%L
,则可以选择将它们显示为
NULL
。但是,如果您使用该格式说明符,它将显示单引号,在某些情况下需要强制转换

根据格式字符串格式化参数。此函数类似于C函数sprintf。看

但在我看来,最好的解决方案是使用
USING
子句并在其中传递值。它看起来有点像预处理语句,保护您不受SQL注入的影响,但不像预处理语句那样缓存计划。在的文档中有一些简单的示例说明了如何做到这一点

EXECUTE'SELECT count(*)FROM mytable WHERE inserted_by=$1 AND inserted
EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2'
   INTO c
   USING checked_user, checked_date;