I have a hierarchy table:
CREATE TABLE tmp.myTable
(
[Id] int IDENTITY(1,1) PRIMARY KEY ,
[Desc] nvarchar(50) NOT NULL,
[Lvl] TINYINT NOT NULL,
[ParentId] int REFERENCES tmp.myTable(Id)
)
I have to insert the data one by one, which can be time-consuming on a slow connection or over VPN etc
Let's say we want to insert this row of hierarchy:
A > AB > ABC > ABCD
These are the statements:
INSERT INTO tmp.myTable ([Desc],[Lvl],[ParentId]) VALUES('A',1,NULL);
INSERT INTO tmp.myTable ([Desc],[Lvl],[ParentId])
SELECT 'AB',2,Id FROM tmp.myTable WHERE [Desc]='A'
INSERT INTO tmp.myTable ([Desc],[Lvl],[ParentId])
SELECT 'ABC',3,Id FROM tmp.myTable WHERE [Desc]='AB'
INSERT INTO tmp.myTable ([Desc],[Lvl],[ParentId])
SELECT 'ABCD',4,Id FROM tmp.myTable WHERE [Desc]='ABC'
I was wondering if there is a better way to do this.
One idea is to make ID column INT and not IDENTITY and then control it on the application side, but I don't like that idea since if more than a user tries to do inserts, the transaction will fail or we may even make mistakes in inserting ParentIds