I tried to make a SQL query with a nested SELECT on the SAME table (UID in the table are polymorphic).
The problem is that my nested SELECT returns NULL always.
Here is the query :
SELECT
Ent.UID,
Measurement.MeasurementClass AS Type,
Substation.TG8000_Name AS Station,
SUBSTRING(Measurement.TG8000_Name,1,5) AS Travee,
SUBSTRING(Measurement.TG8000_Name,6,8) AS Equipement,
Measurement.ClonedFromMeasurement,
(SELECT TOP 1 TG8000_Name
FROM [BD_Sonel_PTG].[dbo].[Measurement]
WHERE (UID=Measurement.ClonedFromMeasurement) ) AS Template,
LongName.LongName AS Description,
Measurement.MeasurementUnit AS Units,
MeasurementLimit.LowLimit,
MeasurementLimit.HighLimit,
RTU.TG8000_Name AS RTUName,
RTU.RTUProtocol,
RTU.Configuration AS RTUConfiguration,
Telemetry.Address,
Measurement.DisplayName AS Display,
REPLACE(Measurement.MeasurementClass,' ','')+':'+REPLACE(Substation.TG8000_Name,' ','')+'.'+REPLACE(Measurement.TG8000_Name,' ','') AS Tren
FROM EntityName Ent
LEFT JOIN LongName ON Ent.UID = Longname.UID /* chaque point possède une description pour une langue donnée */
LEFT JOIN Measurement ON Ent.UID = Measurement.UID /* chaque point de type measurement possède des infos suppl dansla table Measurement */
LEFT JOIN Substation ON Measurement.Substation = Substation.UID /* chaque point est lié à l'UID d'une station (Table Substations) */
LEFT JOIN Telemetry ON Telemetry.DataSourceFor = Ent.UID /* 1 point télémétré est lié à une entrée de Telemetry (DataSourceFor) */
LEFT JOIN MeasurementLimit ON Ent.UID = MeasurementLimit.UID /* Chaque point de type measurement est lié à des paramètres limites */
LEFT JOIN RTU ON Telemetry.RTU = RTU.UID /* chaque point télémétré est associé à un l'UID d'un RTU dont les paramètres sont dans la table RTU */
/* LEFT JOIN EntityName Ent2 ON Ent.UID = Measurement.ClonedFromMeasurement*/
WHERE Ent.EntityType = 'Measurement'
ORDER BY Substation.TG8000_Name, Measurement.TG8000_Name;
GO
When I execute the nested Select with a hardcoded value as 9616, it works !
... (SELECT TOP 1 TG8000_Name
FROM [BD_Sonel_PTG].[dbo].[Measurement]
WHERE (UID='9616') ) AS Template,
...
So I suppose it is the access to Measurement.ClonedFromMeasurement which doesn’t work…
But as you see in the query, I also outputted the value of Measurement.ClonedFromMeasurement to see what in there, and I recieve correctely my value of 9616 (which is changing from line to line).
How can I access to Measurement.ClonedFromMeasurement in my nested query ?
Try doing a self join for this
OR