Wednesday, December 9, 2009

While loop in sql

Here is how to do while loop in sql:


--script to copy UserOrganisationId record from User table to User_Organisation

Declare @UserID as int

Declare @MaxUserID as int

Declare @OrgID int

select @UserID = MIN(intuserid) from [user]

select @MaxUserID = MAX(intuserid) from [user]

WHILE (@UserID <= @MaxUserID)

BEGIN

if exists(Select * from [user] where intuserid=@UserID)

begin

select @UserID=intuserid, @OrgID=UserOrganisationId

from [user] where intuserid = @UserID

if @orgID is not null and @orgID > 0

begin

INSERT INTO User_Organisation (UserID, OrganisationID, IsDefaultOrganisation)

VALUES (@UserID, @OrgID, 1)

end

end

set @UserID=@UserID+1

END

-- alternative script

INSERT INTO User_Organisation (UserID, OrganisationID, IsDefaultOrganisation)

SELECT intUserID, UserOrganisationId, 1

FROM [User]

WHERE (UserOrganisationId IS NOT NULL) AND (UserOrganisationId > 0)

blog comments powered by Disqus