With my limited SQL knowledge, I'm unable to figure this out. What's wrong with the following:
DECLARE @Id int
DECLARE @Name varchar(40)
WHILE EXISTS
(
SELECT TOP 1 @Name = Name, @Id=ID FROM MyTable c WHERE <CONDITION>
)
BEGIN
SOME MORE SQL using @Id and @Name
END
I get a syntax error near @Name = Name
EDIT
To add more context to the problem, I have two tables named Category (ID, Name, ParentID) and Account(ID, Name, CategoryID).
There are 3 levels of Categories.
- Root
- Category
- SubCategory
This is achieved using a recursive relation (ParentID > CategoryID). Problem to solve is that if there are any Accounts that belongs to a Category X (level 2), we must
- Create a SubCategory Y (level 3) with the same name as X
- Make Y a child of that X
- Move all Accounts from X to Y
Here is the original script I have written:
DECLARE @Id int
DECLARE @Name varchar(40)
WHILE EXISTS(
SELECT TOP 1 @Name=Name, @Id=CategoryID FROM Category c WHERE
ParentID = (SELECT TOP 1 CategoryID FROM Category WHERE Name = 'Root') AND
(SELECT COUNT(*) FROM Account WHERE CategoryID = c.CategoryID) > 0
)
BEGIN
INSERT INTO Category(Name, ParentID) VALUES(@Name, @Id)
UPDATE Account SET CategoryID = @@IDENTITY WHERE CategoryID = @Id
END
Incorrect syntax near '='.MyTable?ID int, Name varchar(40), ParentID int