How to extract all table names and aliases from Tsql select statements in .net

六眼飞鱼酱① 提交于 2019-12-11 17:06:06

问题


All of my tenanted tables in sql server have a field customer_id. I'm attempting to write an interceptor for NPoco that will extract all table and alias names from the query. match it to an exception list of tables that are not tenanted, and modify the select to check the tenant key of all tenanted tables in the where clause.

I'm having a really hard time finding a sql parser that can extract table names and aliases from a sql statement.

A good solution would parse the following statement.

SELECT fis.OrderDateKey, SUM(fis.SalesAmount) AS TotalSales
FROM FactInternetSales fis
  Join product on fis.productid = product.productid
  where p.name like 'prefix%'
  GROUP BY fis.OrderDateKey
  HAVING fis.OrderDateKey > 20010000
  ORDER BY fis.OrderDateKey;

Would provide enough information for me to reliably construct a dictionary with 2 items {"FactInternetSales", "fis"} and {"product", "product"}

So far I have only found tokenizers that only know types that are too generic for me to rely upon. (ie keyword, identifier, operator, text). Is there anything out there that can do this sort of work in .net. Or are there better strategies to append these tenant checks to every query ran?


回答1:


This answer was useful in finding a solution to my problem.

If anyone is interested, this is my first pass. We actually use systemId as our tenant, so you will see that in the code. So far, the only queries I've found that it doesn't handle are those with subqueries. I'm digging into that problem now, but I may not add it in, as the vast majority of what my team needs is handled here.




回答2:


Sorry, but I have some doubts about.

  1. You have all the tables in the server, right? in sys.tables you have all the table names. in sys.columns are the name of columns of that tables, caution with the schema. In sys.columns also have user_types... You could Match this tables with the select for find tables and columns. There are views system tables too, and of stored procedures, even the content...
  2. If the tables doesn't exists, the selects doesn't work, so I don't understand the question.
  3. If you use sql server profile (if you can), it could catch more information about any query to the database.
  4. In StackOverflow you have to write some of the code or a link related with some work about you your question. howto.

Ask me any question, hope to help!! :)



来源:https://stackoverflow.com/questions/45513029/how-to-extract-all-table-names-and-aliases-from-tsql-select-statements-in-net

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