将SQL关键字值存储在变量中

时间:2018-12-04 06:07:56

标签: python sql-parser

如何在各个变量中存储SQL关键字的值。

示例SQL:

UPDATE dbname.tablename  
SET 
alias1=T1.col1,
alias2=T1.col2
FROM
(SELECT
T1.col_id,
T1.col_dt,
T1.col_ts
FROM 
dbname.tablename T1
WHERE 
T1.col_dt is NULL
AND T1.col_ts IS NOT NULL
AND
T1.col='ABC'
and  NOT EXISTS
(SELECT '1' FROM dbname.tablename T2
WHERE T2.col = 'ABC'
AND T1.col_id=T2.T1_col_id)
) T3
WHERE R.col_id=T3.col_id; 

样本输出:

updte=dbname.tablename
set=alias1=T1.col1,alias2=T1.col2
frm=(SELECT
T1.col_id,
T1.col_dt,
T1.col_ts
FROM 
dbname.tablename T1
WHERE 
T1.col_dt is NULL
AND T1.col_ts IS NOT NULL
AND
T1.col='ABC'
and  NOT EXISTS
(SELECT '1' FROM dbname.tablename T2
WHERE T2.col = 'ABC'
AND T1.col_id=T2.T1_col_id)
) T3
where=R.col_id=T3.col_id

还有一种方法可以识别所有子查询并对其进行归类,如果它是from子句或where子句的一部分?

import sqlparse
query_tokens.tokens

以上给出的值如下,但不能存储每个关键字的值,例如update和关键字的其余部分。

输出:

[<Newline ' ' at 0x385DA08>, <DML 'UPDATE' at 0x385DA68>, <Whitespace ' ' at 0x385DAC8>, <Identifier 'tablen...' at 0x385CDE0>, <Whitespace ' ' at 0x385DC48>, <Keyword 'set' at 0x385DCA8>, <Newline ' ' at 0x385DD08>, <IdentifierList 'TABLEN...' at 0x386B048>, <Newline ' ' at 0x3867228>, <Keyword 'FROM' at 0x3867288>, <Whitespace ' ' at 0x38672E8>, <Identifier 'tablen...' at 0x385CF48>, <Whitespace ' ' at 0x3867528>, <Where 'where ...' at 0x385CD68>]

0 个答案:

没有答案