我在编写查询以选择字符串时感到震惊。我要发布的查询是示例数据
Declare @tbl table (tblname varchar(20),Query VARCHAR(MAX))
Insert into @tbl (tblname,Query) values ('Employee','select EmpId,
(Select top 1 Dept_ID from Stg.Dept
where Deptid = Deptid) Dept_ID,
(Select top 1 Dept_ID from Stg.Sub_dept
where Deptid = D.Deptid) SubDept_ID
from stg.Employee E
left join stg.Dept D
ON D.EMPID = E.EmpID
WHERE EMPID = (Select EMPID from stg.dept where Deptid = Deptid)')
查询:
select tblname,SUBSTRING(LTRIM(SUBSTRING(Query, CHARINDEX('FROM', Query)+4, LEN(Query))),
CHARINDEX('.', LTRIM(SUBSTRING(Query, CHARINDEX('FROM', Query)+4, LEN(Query))))+1,
CHARINDEX(' ',
SUBSTRING(LTRIM(SUBSTRING(Query, CHARINDEX('FROM', Query)+4, LEN(Query))),
CHARINDEX('.', LTRIM(SUBSTRING(Query, CHARINDEX('FROM', Query)+4, LEN(Query))))+1, LEN(Query)))-1) from
@tbl
结果:
tblname Req_tbl
Employee Dept
实际上,此查询是从该查询列的子查询中选择 stg.Dept 表名。我真正想要的是选择主表 stg.Employee 。
输出:
tblname Req_tbl
Employee Employee
可以请您提出建议
答案 0 :(得分:0)
这不是100%清楚的,但是您要尝试执行的操作似乎是解析查询以确定由@ tbl.tblname定义的对象。该查询中存在FROM子句的查询。例如-对于“雇员”,您正在寻找“ stg.employee”(不包括架构)。
如果我正确理解这一点,则可以使用诸如DelimitedSplit8K之类的拆分器轻松完成此操作,并执行以下操作:
Declare @tbl table (tblname varchar(20),Query VARCHAR(MAX))
Insert into @tbl (tblname,Query) values ('Employee','select EmpId,
(Select top 1 Dept_ID from Stg.Dept
where Deptid = Deptid) Dept_ID,
(Select top 1 Dept_ID from Stg.Sub_dept
where Deptid = D.Deptid) SubDept_ID
from stg.Employee E
left join stg.Dept D
ON D.EMPID = E.EmpID
WHERE EMPID = (Select EMPID from stg.dept where Deptid = Deptid)')
SELECT TOP (1) t.tblname, req_table = t.tblname
FROM @tbl AS t
CROSS APPLY dbo.delimitedSplit8K(t.Query,CHAR(10)) AS s
WHERE PATINDEX('%[^a-zA-Z]from %'+t.tblname+'%', s.item) > 0;
但是,这里的问题是,这取决于您的T-SQL代码的统一程度-这可能变得复杂而繁琐。