她对我将如何处理这个问题做了一个模糊的概述。它做了很多假设,缺少关键组件,没有以任何方式进行调试,并且完全依赖于那些你无法控制的查询,这些查询对于难以确定的好值是“好”的。
假设:一组查询看起来像这样:
Level1Q: select * from users where name=:param_user
Level2Q: select * from projects where id=:param_id
Level3Q: select * from details where id=:param_id
Level4Q: <etc>
因此,对于“3 级”查询,您需要生成以下内容:
;WITH
Level1Q as (select * from users where name=:param_user)
,Level2Q as (select * from projects where id=:param_id)
,Level3Q as (select * from details where id=:param_id)
select * from Level3Q
这个,或者类似的东西,应该产生那个查询:
DECLARE
@Command nvarchar(max)
,@Query nvarchar(max)
,@Loop int
,@MaxDepth int
,@CRLF char(2) = char(13) + char(10) -- Makes the dynamic code more legible
SET @Command = 'WITH'
-- Set @MaxDepth to the level you want to query at
SET @MaxDepth = 3
SET @Loop = 0
WHILE @Loop < @MaxDepth
BEGIN
SET @Loop = @Looop + 1
-- Get the query for this level
SET @Query = <next query>
SET @Command = replace(@Command + @CRLF
+ case @Loop when 1 then ' ' else ' ,' end
+ 'Level<<@Loop>>Q as (' + @Query + ')'
,':param_user', <appropriate value) -- Only used when @Loop = 1
,':param_id', 'Level<<@Loop>>Q.id') -- This assumes the link to the prior query is always by a column named "id"
,'<<@Loop>>', @Loop) -- Done last, as the prior replace added another <<@Loop>>
END
-- Add the final pull
SET @Command = @Command + @CRLF + replace(' select * from Level<<@Loop>>Q', '<<@Loop>>', @Loop - 1)
-- The most important command, because debugging this mess will be a pain
PRINT @Command
--EXECUTE sp_executeSQL @Command