1

Whenever I look for duplicate values in a column, I write a little script like this:

SELECT COL1, COUNT(COL1)
FROM TABLE1 
GROUP BY COL1
HAVING COUNT(COL1) >1

It works, but I have to type. So, I decided to try parameters:

DECLARE @table VARCHAR(100)
DECLARE @column VARCHAR(100)

SET @table = 'TABLE1';
SET @column = 'COLUMN1';

SELECT @column, COUNT(@column)
FROM @table
GROUP BY @column
HAVING COUNT(@column) >1

SQL doesn't like this. It states: Msg 1087, Level 16, State 1, Line 34. Must declare the table variable "@table".

If I slightly modify to use the table name:

DECLARE @column VARCHAR(100)
SET @column = 'COLUMN1';

SELECT @column, COUNT(@column)
FROM TABLE1
GROUP BY @column
HAVING COUNT(@column) >1

I receive this error: Msg 164, Level 15, State 1, Line 51 Each GROUP BY expression must contain at least one column that is not an outer reference.

What am I doing wrong?

1 Answer 1

2

I would probably use a dynamic query to accomplish something like this.

DECLARE @table VARCHAR(100)
DECLARE @column VARCHAR(100)
DECLARE @SQL NVARCHAR(max)

SET @table = 'TABLE1';
SET @column = 'COLUMN1';
SET @SQL = 
'SELECT ' + @column +' , COUNT( ' + @column + ')
 FROM ' + @table + '
GROUP BY ' + @column + '
HAVING COUNT(' + @column + ') >1'

EXEC sp_executesql @sql
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, great solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.