Wednesday, June 6, 2012

how to use a cursor in SQL to nest other queries in a loop

declare @lanlogin varchar(max)
declare @userguid varchar(max)
DECLARE curs CURSOR FOR SELECT Logon FROM Bar
OPEN curs
FETCH NEXT FROM curs into @lanlogin
WHILE @@FETCH_STATUS = 0
   BEGIN
      SELECT @userguid = FooID FROM Foo WHERE Logon = @lanlogin
      UPDATE Bar SET FooID = @userguid WHERE Logon = @lanlogin
      FETCH NEXT FROM curs into @lanlogin
   END
CLOSE curs
DEALLOCATE curs

No comments:

Post a Comment