1

I want to check duplicate Id validation in sql server, that validation grid display row number , validation message & duplicate ID from sql server

I am not able to understand that how can I do it ?

Help is really appreciate

Create Table

    CREATE TEMPORARY TABLE IF NOT EXISTS Tbl_Student
    (RowID INT PRIMARY KEY auto_increment, StudentID BIGINT);

Insert Records

Insert into Tbl_Student(RowID,StudentID) values (1,101)
Insert into Tbl_Student(RowID,StudentID) values (2,102)
Insert into Tbl_Student(RowID,StudentID) values (3,101)
Insert into Tbl_Student(RowID,StudentID) values (4,102)
Insert into Tbl_Student(RowID,StudentID) values (5,103)


enter image description here

Please let share if any solution over there

Thank you

shivani
  • 980
  • 1
  • 8
  • 29

4 Answers4

1

Try the following Query,

SELECT RowID, CONCAT('StudentID ',StudentID, ' is Duplicate) AS Error FROM Tbl_Student WHERE StudentID IN (SELECT StudentID FROM Tbl_Student GROUP BY StudentID  HAVING COUNT(*) > 1)
Vahid Farahmandian
  • 6,081
  • 7
  • 42
  • 62
0

Here is T-SQL code, you might need to transform it to MySql format:

Select * from(
      Select RowId, Count(*) Over(Partition By StudentId Order By RowId) as Cnt From [YourTable]
) as K
Where Cnt>1

You can also use Row_Number or Count aggregate function to achieve the same result too.

Here is plenty of MySql solutions for this problem:

Find duplicate records in MySQL

Vahid Farahmandian
  • 6,081
  • 7
  • 42
  • 62
0

To display the duplicates I would do:

select
  RowID, 
  concat('Student ', StudentID, ' is duplicate') as StudentID
from Tbl_Student where StudentID in (
  select StudentID from Tbl_Student group by StudentID having count(*) > 1
)
The Impaler
  • 45,731
  • 9
  • 39
  • 76
0

You could use a join on the suquery having count of strundet id > 1

  select id,  student_id, concat('Stundent id' , student_id, ' is duplicated')
  from  my_table m
  inner join  (
    select student_id 
    from my_table  
    group by student_id 
    having count(*) > 1  
  ) t on t.student_id  = m.student_id
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107