c# - 从 SQL 查询中获取参数名称

标签 c# asp.net regex asp.net-4.0

后端是 PostgreSQL 服务器 9.1。

我正在尝试构建 AdHoc XML 报告。报告文件将包含 SQL 查询,所有查询都必须以 SELECT 语句开头。 SQL 查询将有参数。根据关联列的数据类型,这些参数将相应地呈现给用户以提供值。

粗略的 SQL 查询:

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;

我想从查询字符串中获取列名和参数的列表,并将它们放入一个字符串数组中,稍后再处理。

我只能使用以下正则表达式匹配参数:

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

预期匹配:

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

如何立即匹配“@Parameter”、“=”和“BETWEEN”?

最佳答案

我知道有点晚了,但为了 future 的研究:

我认为这个 Regex 符合您的目的:

(\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] 
`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`

关于c# - 从 SQL 查询中获取参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18000874/

相关文章:

c# - 具有空白元素的 XML 类型的 SQLParameter,是否丢失了空白?

c# - 以 ASP.NET MVC 表格形式动态添加行

python - 多次匹配非捕获组

javascript - 验证按键上的日期不起作用

c# - 将 where 子句添加到嵌套的 Linq 选择

c# - 不正确的 float 减法结果

c# - 执行多条件时出错,未知列 - Mono + NHibernate + MySQL

javascript - 使用jquery隐藏元素占用页面空间

asp.net - 如何更正部分回发时丢失的 ASP.NET Webform jquery 引用

javascript - 用正则表达式替换捕获的空格未知次数