2014-01-23 64 views
0

我有一个查询,我在SQL中开发并运行正常,但是当我将查询放入SQL Server(或.Net)查询生成器时,它会生成错误。这里要说的是像我写SQL Server查询生成器错误?

此查询的例子我写什么(工作)

Select Case when Table1.[Col 1] is null then Table2.[Col 1] Else Table1.[Col 1] END as 'col1' From 
(Select Sum(Table3.[Col 1]) as 'col 1', Table3.[groupby col] from Table3 Group by Table3.[groupbycol]) as Table1 FULL OUTER JOIN (Select Sum(Table3.[Col 1]) as 'col 1', 'Total' as 'groupby col' from Table3) as Table2 ON Table1.[groupby col] = Table2.[groupby col] 

但当时如果我在SQL或asp.net查询生成器打开这个“改进“它使中断查询,现在看起来是这样的

Select 
    Case 
     when Table1. 'Col 1' is null 
     then Table2. 'Col 1' 
     Else Table1. 'Col 1' 
    END as 'col1' 
From 
    (Select 
     Sum(Table3.[Col 1]) as 'col 1', 
     Table3.[groupby col] 
    from 
     Table3 
    group by 
     Table3.[groupbycol]) as Table1 
FULL OUTER JOIN 
    (Select 
     Sum(Table3.[Col 1]) as 'col 1', 
     'Total' as 'groupby col' 
    from Table3 as Table3_1) as Table2 ON Table1. 'groupby col' = Table2. 'groupby col' 

不再适用,因为它,因为它取代了[]与和列名前添加一个空格和表3创建别名在第二个查询中,然后不会将该别名分配给使用该表的其他时间

任何人都知道是什么原因造成这似乎每次我打开一个查询构建器它可能搞砸查询

感谢

+1

引用标识符 – Jodrell

回答

0

字符串字面有可能成为恼人的,因为列别名都在deprecation list为SQL Server 。尽管不是便携式语法,但我一直都是SQL Server中的Alias = Expression语法的粉丝。 Aaron Bertrand在他的文章Bad Habits to Kick : Using AS instead of = for column aliases中也做了一个很好的例子。

考虑到这一点我会重写整个查询为:

SELECT Col1 = ISNULL(table1.Col1, table2.Col1) 
FROM ( SELECT Col1 = SUM(table3.[Col 1]), 
        GroupByCol = Table3.[groupby col] 
      FROM Table3 
     ) table1 
     FULL OUTER JOIN 
     ( SELECT Col1 = SUM(table3.[Col 1]), 
        GroupByCol = 'Total' 
      FROM Table3 
     ) table2 
      ON Table1.GroupByCol = Table2.GroupByCol; 

或者

SELECT ISNULL(table1.Col1, table2.Col1) AS Col1 
FROM ( SELECT SUM(table3.[Col 1]) AS Col1, 
        Table3.[groupby col] AS GroupByCol 
      FROM Table3 
     ) AS table1 
     FULL OUTER JOIN 
     ( SELECT SUM(table3.[Col 1]) AS Col1, 
        'Total' AS GroupByCol 
      FROM Table3 
     ) AS table2 
      ON Table1.GroupByCol = Table2.GroupByCol; 

我也怀疑你实际上能达到的结果你是使用ROLLUP后:

SELECT Col1 = SUM(table3.[Col 1]), 
     GroupByCol = ISNULL(Table3.[groupby col], 'Total') 
FROM Table3 
GROUP BY Table3.[groupby col] 
WITH ROLLUP; 
+0

我不知道字符串在SQL中折旧(实际上我认为这是使用它们的好习惯),但我认为我会坚持认为=因为这是我与其他人合作的原因 – jgok222