Is it possible to recreate the raw SQL from the tokens? #127
-
Hi, Is it possible to reconstruct the raw SQL from the tokens? I want to take a SELECT query and replace the field list with a COUNT(*) field and then reconstruct the SQL so I can execute it against the DB, is this possible? Regards, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
The intention would be yes. Doing your replacement will be challenging on more complex SELECT statements using only TSQLToken's from TSQLTokenizer however, trying to keep track of if you're in the column list or not, especially considering CTE's. The simplest way, if you still have the original SQL as a string, would be to use TSQLStatementReader to parse a TSQLSelectStatement. Then, you can look at the SELECT property, and its Tokens property, which would contain your column list, after a few keyword tokens like SELECT, TOP, DISTINCT. You might choose to drop some of those also. But once you find the first token that you want to start dropping, you can get it's BeginPosition , and replace through the SELECT property's EndPosition , with " COUNT(*) ". There may be SELECT statements where the parsing is not yet perfect, which you can report back here as bugs, but the intention would be that it parses the column list correctly. Piecing back SQL from a list of TSQLToken's is a different challenge, and doesn't seem like it would solve your problem. Bruce Dunwiddie |
Beta Was this translation helpful? Give feedback.
-
Thank you for your response, I came to the same conclusion after looking at the TSQLTokenizer output! I thought I would post the results of my challenge here so that any flaws in my approach can be identified by other devs and it also might help someone else trying to do something similar in the future. My use case is that I'm creating a SQL statement to use as a data source for a JSON configured bulk import process. Everything was fine when my SQL was Here's a real example of an input query
The above query needs to be transformed into
The following code seems to be working in my specific use case: -
|
Beta Was this translation helpful? Give feedback.
The intention would be yes.
Doing your replacement will be challenging on more complex SELECT statements using only TSQLToken's from TSQLTokenizer however, trying to keep track of if you're in the column list or not, especially considering CTE's.
The simplest way, if you still have the original SQL as a string, would be to use TSQLStatementReader to parse a TSQLSelectStatement. Then, you can look at the SELECT property, and its Tokens property, which would contain your column list, after a few keyword tokens like SELECT, TOP, DISTINCT. You might choose to drop some of those also. But once you find the first token that you want to start dropping, you can get it's BeginPosition , and replac…