Advertisement
JanuszKowalski123

10. hierarchyid 8

May 9th, 2024 (edited)
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. CREATE TABLE Renewable_Energy_Devices (
  2. device_id NVARCHAR(26) PRIMARY KEY,
  3. device_status INT CHECK (device_status >= 0 AND device_status <= 6),
  4. device_power DECIMAL(18,0),
  5. company_id INT,
  6. device_location GEOGRAPHY,
  7. device_location_geom GEOMETRY,
  8. device_hierarchy HIERARCHYID,
  9. device_description XML
  10. );
  11.  
  12.  
  13. DECLARE @latitude DECIMAL(9, 6), @longitude DECIMAL(9, 6);
  14. DECLARE @point GEOMETRY;
  15. DECLARE @device_hierarchy HIERARCHYID;
  16. DECLARE @device_description XML;
  17.  
  18. DECLARE @i INT = 1;
  19. WHILE @i <= 50
  20. BEGIN
  21. SET @latitude = RAND() * 180 - 90;
  22. SET @longitude = RAND() * 360 - 180;
  23. SET @point = GEOMETRY::Point(@latitude, @longitude, 4326);
  24.  
  25. -- Tworzenie hierarchii z użyciem losowej wartości dodanej do korzenia
  26. SET @device_hierarchy = HIERARCHYID::GetRoot().GetDescendant(NULL, NULL);
  27.  
  28. SET @device_description = '<description>Device_' + CAST(@i AS NVARCHAR(5)) + '</description>';
  29.  
  30. INSERT INTO Renewable_Energy_Devices (device_id, device_status, device_power, company_id, device_location, device_location_geom, device_hierarchy, device_description)
  31. VALUES (
  32. 'Device_' + CAST(@i AS NVARCHAR(5)),
  33. CAST(RAND() * 6 AS INT),
  34. CAST(RAND() * 1000 AS DECIMAL(18, 0)),
  35. CAST(RAND() * 10 AS INT) + 1,
  36. GEOGRAPHY::Point(@latitude, @longitude, 4326),
  37. @point,
  38. @device_hierarchy,
  39. @device_description
  40. );
  41.  
  42. SET @i = @i + 1;
  43. END;
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50. WITH DeviceHierarchyCTE AS (
  51. SELECT
  52. device_id,
  53. device_hierarchy,
  54. CAST('/' + device_id + '/' AS NVARCHAR(MAX)) AS hierarchy_path,
  55. CAST('/' + device_id + '/' AS NVARCHAR(MAX)) AS device_path,
  56. 1 AS hierarchy_level
  57. FROM
  58. Renewable_Energy_Devices
  59. WHERE
  60. device_hierarchy = HIERARCHYID::GetRoot()
  61.  
  62. UNION ALL
  63.  
  64. SELECT
  65. red.device_id,
  66. red.device_hierarchy,
  67. dhc.hierarchy_path + red.device_id + '/' AS hierarchy_path,
  68. dhc.device_path + red.device_id + '/' AS device_path,
  69. dhc.hierarchy_level + 1
  70. FROM
  71. Renewable_Energy_Devices AS red
  72. INNER JOIN
  73. DeviceHierarchyCTE AS dhc ON dhc.device_hierarchy.IsDescendantOf(red.device_hierarchy) = 1
  74. )
  75. SELECT
  76. device_id,
  77. hierarchy_path,
  78. device_path,
  79. hierarchy_level
  80. FROM
  81. DeviceHierarchyCTE
  82. ;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement