简体   繁体   中英

How to get a string variable in sql Postgresql

Can someone help-me set up an SQL command that retrieves only the value of the first occurrence of "cost" in a string like the example below.

See below two results returned from a table where I store sql query execution plan. I use Postgres. The word cost always comes at the beginning, but it does not always come in the same position, so you can not simply do substring (...). I think you should find the initial and final position every time, to be able to extract only the cost value. If anyone can help me, the expected result for the example below is:

select (.... )
-----------------
cost=399301  (only this)

----------------------SAMPLE STRING SOURCE ------------------

Sort  (cost=399301.55..399301.57 rows=6 width=36)
  Sort Key: l_returnflag, l_linestatus
  ->  HashAggregate  (cost=399301.21..399301.48 rows=6 width=36)
        ->  Seq Scan on h_lineitem  (cost=0.00..250095.98 rows=5968209 width=36)
              Filter: (l_shipdate <= (to_date('1998/12/01'::text, 'YYYY/MM/DD'::text) - '10 days'::interval day))

-------------------- SECOND SAMPLE --------------------------------

Aggregate  (cost=7922058.70..7922058.71 rows=1 width=16)"
  ->  Hash Join  (cost=1899763.92..7922058.69 rows=1 width=16)"
        Hash Cond: (h_lineitem.l_partkey = h_part.p_partkey)"
        Join Filter: (((h_part.p_brand = 'Brand#13'::bpchar) AND (h_part.p_container = ANY ('{"SM CASE","SM BOX","SM PACK","SM PKG"}'::bpchar[])) AND (h_lineitem.l_quantity >= 4::double precision) AND (h_lineitem.l_quantity <= 14::double precision) AND (h_ (...)"
        ->  Seq Scan on h_lineitem  (cost=0.00..235156.84 rows=211094 width=32)"
              Filter: ((l_shipmode = ANY ('{AIR,"AIR REG"}'::bpchar[])) AND (l_shipinstruct = 'DELIVER IN PERSON'::bpchar))"
        ->  Hash  (cost=1183158.46..1183158.46 rows=35278997 width=33)
->  Seq Scan on h_part  (cost=0.00..1183158.46 rows=35278997 width=33) Filter: (p_size >= 1)"

Best Regards

Assuming the plans are stored in a table named plan_table in a column named execution_plan you can use the following:

select replace(substring(execution_plan from '\(cost=[0-9]+'), '(cost=', '')
from plan_table;

The substring(...) returns the first occurrence of (cost= and the replace is then used to remove that prefix.

I get successful and the solution, the obcjetive was get the value 27726324.41, the Expression Regular final developted is:

select substring('Aggregate (cost=27726324.40..27726324.41 Rows' from '[.]Y*([0-9]+.?[0-9]{2})') 

RESULT 27726324.41

Thanks a_horse_with_no_name and anothers that help-me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM