我需要確定大量不同列中的重複項。我嘗試使用下面的代碼,而不是輸入每個列名稱。這稍微更有效,因爲我只需要輸入一次列名。但是,我收到此錯誤: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
[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 /) –
如果你想使用變量作爲列名,你將不得不使用動態sql。看[動態sql的詛咒和祝福](http://www.sommarskog.se/dynamic_sql.html) – Taryn