很多时候,我想用一个@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
。
后者不太舒服,但是两者都需要从原始代码中进行很多更改。
是否可以在不使用以上两个选项中的任何一个的情况下,在select
中调试cte
台?
答案 0 :(得分:2)
使用您的代码示例,另一种方法是:
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
编辑以回应:
我当时在想IDE具有一些晦涩的隐藏功能, 让我查看cte的结果,而不必更改整体 查询
在这种情况下,答案是否定的。 IDE中没有类似的东西。
答案 1 :(得分:2)
您也可以将很长的查询也包装到cte中,然后在底部只需注释掉一行即可。
import numpy as np
import pandas as pd
from sklearn.neighbors import KDTree
np.random.seed(0)
#since you have df1 and df2, you will want to convert the dfs to array here with
#X=df1['x'.'y','z'].to_numpy()
#Y=df2['x','y','z'.to_numpy()
n=11 #n=number of dimensions in your sample
X = np.random.random((10, n)) # 10 points in n dimensions
Y = np.random.random((10, n))
tree = KDTree(Y, leaf_size=2)
indices=[]
#for i in range(len(X)):
#loop though the x array and find the closest point in y to each x
dist, ind = tree.query(X, k=1)
#indices.append(ind)
df1=pd.DataFrame(X)
##set the labels to the closest point to each neighbor
df1['label']=ind
最后,如果您使用的是SQL Management Studio,请使用快捷键;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.
注释掉行,并使用Ctrl+K+C
取消注释。