使用变量调试 CTE?

Debug CTE with variables?

很多时候我想用@variable 查看CTE 中某个查询的结果,而不必通过在末尾添加select * from cte 来改变整个事情。

一个例子是这样的:

declare @From date
declare @To date
declare @city varchar(20)
declare @st varchar(5)

// Lots of code that sets all the @variables

;with cteSales as
(
    select * from MyTable 
    where 
    From = @From and To = @To and 
    salesman = @salesman and city = @city and st = @st
) 
//HERE GOES A LONG QUERY THAT USES cteSales

我知道在 CTE 中调试查询的唯一方法是 1) 用值替换变量并执行查询或 2) 在 cteSales 之后注释所有内容并添加 select * from cteSales.

后者不太舒服,但都需要对原始代码进行大量更改。

是否可以在不使用上述两个选项的情况下在 cte 中调试 select 语句?

使用您的代码示例的另一种选择是:

declare @From date
declare @To date
declare @city varchar(20)
declare @st varchar(5)

// Lots of code that sets all the @variables

--;with cteSales as   --comment these two lines out for testing
--(
    select * from MyTable 
    where 
    From = @From and To = @To and 
    salesman = @salesman and city = @city and st = @st  --highlight the code up to here and execute
) 
//HERE GOES A LONG QUERY THAT USES cteSales

编辑以回应:

I was thinking that the IDE had some obscure hidden feature that would let me view the results of a cte without having to alter the whole query

在那种情况下,答案是否定的。 IDE.

中没有这样的东西

你也可以把很长的查询包成一个cte,然后在底部你所要做的就是注释掉一行。

;with cteSales as
(
    select * from MyTable 
    where 
    From = @From and To = @To and 
    salesman = @salesman and city = @city and st = @st
) 
, cteVeryLongQuery as (
    //HERE GOES A LONG QUERY THAT USES cteSales
)
SELECT * FROM cteVeryLongQuery
-- SELECT * FROM cteSales -- Uncomment this for debugging `cteSales` and comment out the line above.

最后,如果您使用的是 SQL Management Studio,请使用快捷键 Ctrl+K+C 注释掉行并使用 Ctrl+K+U 取消注释。