nodes(nodeID int) is a list of all nodes. edges(fromNodeID int, toNodeID int) is the relationship between two nodes. Assume the graph is undirected, find all the connected components.
CREATE PROCEDURE getGraph
AS BEGIN
CREATE TABLE graphs (node int, id int);
DECLARE @graphID int;
SET @graphID = 0;
WHILE ((SELECT COUNT(*) FROM graphs) < (SELECT COUNT(*) FROM nodes))
BEGIN
CREATE TABLE currentGraph (node int);
CREATE TABLE temp(node int);
DECLARE @start int;
SET @start = (SELECT TOP (1) n.paperID
FROM nodes n
WHERE n.paperID NOT IN (SELECT * FROM graphs));
INSERT INTO currentGraph VALUES (@start);
INSERT INTO temp (node) VALUES (
SELECT e.citedPaperID
FROM currentGraph cg, edges e
WHERE cg.node = e.paperID
);
/* If there is any new node, keep searching for current graph*/
WHILE ((SELECT COUNT(*)
FROM temp
WHERE temp.node NOT IN (SELECT * FROM currentGraph)) <> 0)
BEGIN
INSERT INTO currentGraph (node) VALUES (
SELECT t.node
FROM temp t
WHERE t.node NOT IN (SELECT * FROM currentGraph)
);
DELETE FROM temp;
INSERT INTO temp (node) VALUES (
SELECT e.citedPaperID
FROM currentGraph cg, edges e
WHERE cg.node = e.paperID
);
END
SET @graphID = @graphID + 1;
INSERT INTO graphs (node, id) VALUES ((SELECT DISTINCT cg.node FROM currentGraph cg), @graphID);
END
END
Error message:
[2021-10-02 21:52:07] [S1000][156] Incorrect syntax near the keyword 'SELECT'. [2021-10-02 21:52:07] [42000][102] Incorrect syntax near ')'.
[2021-10-02 21:52:07] [S1000][156] Incorrect syntax near the keyword 'SELECT'. [2021-10-02 21:52:07] [42000][102] Incorrect syntax near ')'.
[2021-10-02 21:52:07] [S1000][156] Incorrect syntax near the keyword 'SELECT'. [2021-10-02 21:52:07] [42000][102] Incorrect syntax near ')'.