2013-07-12 82 views
0

我需要確定大量不同列中的重複項。我嘗試使用下面的代碼,而不是輸入每個列名稱。這稍微更有效,因爲我只需要輸入一次列名。但是,我收到此錯誤:SQL - 將變量用作列名(count)(@variable)

Msg 164,Level 15,State 1,Line 8 每個GROUP BY表達式都必須包含至少一個不是外部引用的列。

declare @TheCount varchar(100) 
set @TheCount = 'Column_1' 
select @TheCount, count(@TheCount) as LineCount 
from staging 
group by @TheCount 
having count(@TheCount) > 1 
order by 2 desc 
+0

[What and Why「this Error」:](http://www.sqlerror.sqlserver-training.com/tag/each-group-by-expression-must-contain-at-least-one -column-that-is-not-an-external-reference /) –

+0

如果你想使用變量作爲列名,你將不得不使用動態sql。看[動態sql的詛咒和祝福](http://www.sommarskog.se/dynamic_sql.html) – Taryn

回答

0

也許這個腳本將是有益的(假設在SQL Server):

CREATE TABLE TEST(
a int 
) 

INSERT INTO TEST VALUES(1) 
INSERT INTO TEST VALUES(1) 
INSERT INTO TEST VALUES(2) 
INSERT INTO TEST VALUES(3) 
INSERT INTO TEST VALUES(4) 
INSERT INTO TEST VALUES(4) 

declare @TheCount varchar(100) 
set @TheCount = 'a' 

EXEC('select ' + @TheCount + ', count(' + @TheCount + ') as LineCount 
     from test 
     group by ' + @TheCount + ' 
     having count(' + @TheCount + ') > 1 
     order by 2 desc') 

你可以試試這個例子here

注意:這是「Dynamic Sql Execution」的一個小示例,這裏有一個link的小解釋。

-1
DECLARE @column_list varchar(4000) = 'column_name1,column_name2,column_name3,etc'; 

DECLARE @sql = ' 
    WITH dups AS (
    SELECT 
     *,ROW_NUMBER() OVER(PARTITION BY '[email protected]_list'+)) AS n 
    FROM table_name 
    SELECT * FROM dups WHERE n > 1'; 

EXEC @sql;