尝试保存视图而不更改查询

时间:2018-11-27 09:29:43

标签: sql sql-server

我在下面编写了一个查询,突出显示了两个具有相同名称但在同一服务器上但位于不同数据库上的表之间的所有差异。

它工作正常并返回预期结果。然后我以为我会将其保存为视图。但是,当我将文本复制到视图中时,它将查询更改为下面的第二个查询。为什么这样做呢?相当令人沮丧。

我的工作查询

;with t as
(
  select SaleDate, id 
  from MyTbl
  group by SaleDate, id
), r as
(
  select SaleDate, id
  from AnotherDatabase.dbo.MyTbl    
  group by SaleDate, id
)
select coalesce(t.SaleDate, r.SaleDate) SaleDate, t.id [t_cp], 
 r.id [r_cp] 
from t full outer join r on t.SaleDate = r.SaleDate and t.id = 
r.id
where t.id is null or r.id is null

查看查询

WITH t AS (SELECT        SaleDate, id
                    FROM            dbo.MyTbl
                    GROUP BY SaleDate, id), r AS
(SELECT        SaleDate, id
  FROM            dbo.MyTbl AS MyTbl_1
  GROUP BY SaleDate, id)
SELECT        COALESCE (t_1.SaleDate, r_1.SaleDate) AS SaleDate, t_1.id AS t_cp, r_1.id AS r_cp
 FROM            t AS t_1 FULL OUTER JOIN
                          r AS r_1 ON t_1.pricedate = r_1.pricedate AND t_1.id = r_1.id
 WHERE        (t_1.id IS NULL) OR
                          (r_1.id IS NULL)

1 个答案:

答案 0 :(得分:0)

我通常使用任何文本编辑器并将代码保存在.sql中。我从来没有遇到过这个问题