SQL - 将变量用作具有计数的列名(@variable)

时间:2013-07-12 16:13:39

标签: sql sql-server variables

我需要确定大量不同列中的重复项。我尝试使用以下代码,而不是键入每个列名称。这稍微有点效率,因为我只需要输入一次列名。但是,我收到了这个错误:

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

2 个答案:

答案 0 :(得分: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

注意:这是“动态Sql执行”的一个小例子,这里有link作为一点解释。

答案 1 :(得分:-1)

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

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

EXEC @sql;