群里看到关于变量替换语句的问题,兴趣来了就研究一下
过滤包含pg_sleep的查询,拼接terminate_backend命令
postgres=# \set querystr pg_sleep
postgres=# \echo :querystr
pg_sleep
postgres=# Select 'select pg_terminate_backend('||pid||');' from pg_stat_activity where state in ('active') and query ~ '%:querystr%';
模糊匹配里面传递变量的sql应该怎么写?
首先来看一下like和~的区别
pg中模糊查询的功能十分强大,正则表达式~和like的模糊查询,这两种方式语义是一样的。
例如这两个语句效果是相同的:
select * from test where col like ‘%xxxxxx%’;
select * from test where col ~ ‘xxxxxx’;
测试数据如下
txdb_default=# create table t1(name text);
CREATE TABLE
txdb_default=# insert into t1 values('afsldgjkl'),('fda%pg_sleep%fds'),('ffpg_sleepff')
INSERT 0 3
![](https://img-blog.csdnimg.cn/123d77bc48f44d8191ee6d2c7092088a.png)
如果使用like的话,使用 %pg_sleep%
![](https://img-blog.csdnimg.cn/14cba34751a542faa23d9581ac3bd14b.png)
![](https://img-blog.csdnimg.cn/16315577f95d44fcbd0639cfa21a6ba2.png)
如果使用~的话,使用 pg_sleep
![](https://img-blog.csdnimg.cn/811a7bc825704b8fbf401ce61e6aaf89.png)
![](https://img-blog.csdnimg.cn/5f4106953e70407cba9994cc6c2c0538.png)