2014-01-23 85 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