Get Parameter Names from SQL Query

混江龙づ霸主 提交于 2019-12-23 08:16:16

问题


The backend is PostgreSQL server 9.1.

I am trying to build AdHoc XML reports. The report files will contain SQL queries, all of which must start with a SELECT statement. The SQL queries will have parameters. Depending upon the data type of the associated columns, these parameters will be accordingly presented to the user to provide value(s).

A rought SQL query:

SELECT * FROM customers
WHERE 
(
    customers.customer_code=@customer_code AND customers.location=@location
    AND customers.type=
    (
        SELECT type from types
        WHERE types.code=@type_code
        AND types.is_active = @type_is_active
    )
    AND customers.account_open_date BETWEEN @start_date AND @end_date
)
OR customers.flagged = @flagged;

I want to get list of the column names and parameters from the query string and put them into a string array and process later.

I am able to match only the parameters using the following regular expression:

@(?)(?<parameter>\w+)

Expected Matches:

customers.customer_code=@customer_code
customers.location=@location
types.code=@type_code
types.is_active = @type_is_active
customers.account_open_date BETWEEN @start_date AND @end_date
customers.flagged = @flagged

How to to match "@Parameter", "=", and "BETWEEN" right away?


回答1:


I know it's a little late, but for future researches' sake:

I think this Regex serves your purpose:

(\w+\.\w+(?:\s?\=\s?\@\w+|\sBETWEEN\s\@\w+\sAND\s\@\w+))

Check this Regex101 fiddle here, and read carefully the explanation for each part of it.

Basically, it first looks for your customer.xxx_yyy columns, and then either for = @variable or BETWEEN @variable1 AND @variable2.

Captured groups:

MATCH 1
1.  [37-75] 
`customers.customer_code=@customer_code`

MATCH 2
1.  [80-108]    
`customers.location=@location`

MATCH 3
1.  [184-205]   
`types.code=@type_code`

MATCH 4
1.  [218-251]   
`types.is_active = @type_is_active`

MATCH 5
1.  [266-327]   
`customers.account_open_date BETWEEN @start_date AND @end_date`

MATCH 6
1.  [333-361]   
`customers.flagged = @flagged`


来源:https://stackoverflow.com/questions/18000874/get-parameter-names-from-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!