2013-08-01 27 views
5

後端是PostgreSQL服務器9.1。從SQL查詢中獲取參數名稱

我想構建AdHoc XML報告。報告文件將包含SQL查詢,所有這些查詢都必須以SELECT語句開頭。 SQL查詢將有參數。根據相關列的數據類型,這些參數將相應地呈現給用戶以提供值。

一個rought SQL查詢:

SELECT * FROM customers 
WHERE 
(
    [email protected]_code AND [email protected] 
    AND customers.type= 
    (
     SELECT type from types 
     WHERE [email protected]_code 
     AND types.is_active = @type_is_active 
    ) 
    AND customers.account_open_date BETWEEN @start_date AND @end_date 
) 
OR customers.flagged = @flagged; 

我想從查詢字符串列名和參數列表,並把它們放入一個字符串數組且稍後處理。

我可以使用下面的正則表達式只匹配參數:

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

預計較量:

[email protected]_code 
[email protected] 
[email protected]_code 
types.is_active = @type_is_active 
customers.account_open_date BETWEEN @start_date AND @end_date 
customers.flagged = @flagged 

如何搭配 「@Parameter」, 「=」,並「BETWEEN」馬上?

+0

如果你使用XML,那麼爲什麼沒有一個參數元素,饒了自己的麻煩? – Romoku

+0

所以你想在你的sql查詢中找到「@ {variablename}」,並將其替換爲用戶想要的實際值? – ganders

+0

嘿,謝謝。 :)你不覺得混合使用SQL和XML會變得相當複雜嗎? –

回答

2

我知道這是一個有點晚,但對於未來的研究的緣故:

我想這正則表達式提供你的目的:

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

檢查this Regex101 fiddle這裏,並仔細閱讀說明它的每個部分。

基本上,它首先查找您的customer.xxx_yyy列,然後查找= @variableBETWEEN @variable1 AND @variable2

捕獲組:

MATCH 1 
1. [37-75] 
`[email protected]_code` 

MATCH 2 
1. [80-108]  
`[email protected]` 

MATCH 3 
1. [184-205] 
`[email protected]_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`