首页 > 解决方案 > 使用变量调试 CTE?

问题描述

很多时候,我想用@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.

后者不太不舒服,但两者都需要从原始代码中更改很多内容。

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

标签: sql-servertsqlsql-server-2008

解决方案


您也可以将非常长的查询包装到 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取消注释。


推荐阅读