0

Good morning community, I am having problems when I run this query from SQL 2018 and Visual basic 2010 shows me the following error "an element with the same key has already been added"

SELECT DESCRIPCION AS nodeText,'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeKey,''AS nodeParentKey FROM DEPARTAMENTO
UNION ALL
SELECT DESCRIPCION AS nodeText,'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeKey,
'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeParentKey FROM PROVINCIA
UNION ALL
SELECT DESCRIPCION AS nodeText,'DIST' + CAST(IDUBIGEO AS VARCHAR) AS nodeKey,
'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeParentKey FROM ubigeo

As I can avoid duplicate elements, I think it is with the DISTINCT clause but I have no idea where this clause can go, please support

4
  • an element with the same key has already been added is not a SQL Server error message. It's coming from VB.NET. – David Browne - Microsoft Apr 5 at 14:10
  • the message comes from visual basic, what happens is that the same code I run for another database works perfect, but with this database with the records already complete it shows me this message – kenny Apr 5 at 14:12
  • Well what data is returned by the query and how are you adding it to a Dictionary in VB? – David Browne - Microsoft Apr 5 at 14:18
  • post the answer, lines below – kenny Apr 5 at 14:27
0

use UNION instead of UNION ALL in this way:

SELECT DESCRIPCION AS nodeText,'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS 
nodeKey,''AS nodeParentKey FROM DEPARTAMENTO
UNION ALL
SELECT DESCRIPCION AS nodeText,'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeKey,
'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeParentKey FROM PROVINCIA
UNION
SELECT DESCRIPCION AS nodeText,'DIST' + CAST(IDUBIGEO AS VARCHAR) AS nodeKey,
'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeParentKey FROM ubigeo

it will remove duplicates

1
  • change what it indicates but this error still appears, if this query eliminates the duplicates then I think the one that is failing is visual, I will not continue testing it yet. – kenny Apr 5 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.