Check for integer in string array

后端 未结 2 969
名媛妹妹
名媛妹妹 2021-01-28 14:06

I am trying to check a string array for existence of a converted integer number. This sits inside of a procedure where:

nc_ecosite is an integer

相关标签:
2条回答
  • 2021-01-28 14:18

    I found the following to provide the desired result:

    IF nc_ecosite in 
    (select (unnest(string_to_array(current_consite, ',')))::integer 
    from current_site_record 
    where current_ecosite_nc::integer = nc_ecosite) THEN
       ecosite := nc_ecosite::integer;
    
    0 讨论(0)
  • 2021-01-28 14:38

    The immediate reason for the problem is that to_char() inserts a leading blank for your given pattern (legacy reasons - to make space for a potential negative sign). Use the FM Template Pattern Modifier to avoid that:

    to_char(nc_ecosite, 'FM999')

    Of course, it would be best to operate with matching data types to begin with - if at all possible.

    Barring that, I suggest this faster and cleaner statement:

       SELECT INTO ecosite  nc_ecosite  -- variable or column??
       WHERE  EXISTS (
          SELECT 1 FROM current_site_record c
          WHERE  current_ecosite_nc::integer = nc_ecosite
          AND    to_char(nc_ecosite, 'FM999') = ANY(current_consite)
          );
    
       IF NOT FOUND THEN  ... -- to replace your ELSIF
    

    Make sure you don't run into naming conflicts between parameters, variables and column names! A widespread convention is to prepend variable names with _ (and never use the same for column names). But you better table-qualify column names in all queries anyway. You did not make clear which is a column and which is a variable ...

    I might be able to optimize the statement further if I had the complete function and table definition.

    Related:

    • Remove blank-padding from to_char() output
    • Variables for identifiers inside IF EXISTS in a plpgsql function
    • Naming conflict between function parameter and result of JOIN with USING clause
    0 讨论(0)
提交回复
热议问题