1

I'm creating a stored procedure in SQL server and want to achieve the following:

I have to look up all the ResourceID's (could be any number of resources) for a certain ClientID in the Resources table. Then I have to insert a row in the Planning table for each ResourceID found.

So I'll have something like

WHILE EXISTS (SELECT ResourceID AS @ResourceID FROM Resources WHERE ClientID = @ClientID)
BEGIN
    INSERT INTO Planning (ResourceID, Date)
    VALUES (@ResourceID, @Date)
NEXT
END

I have already found that using a cursor might be the way, but that doesn't lead me to anything usable

2
  • 3
    for future reference: anytime you find yourself looking for a loop or cursor in SQL Server (especially a cursor) there is almost always a better way. Commented Feb 27, 2012 at 13:39
  • 1
    To help you learn about those better ways:wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them Commented Feb 27, 2012 at 15:54

2 Answers 2

3

No need for loops:

INSERT INTO Planning (ResourceID, Date)
SELECT ResourceID, GETDATE()
FROM Resources 
WHERE ClientID = @ClientID

In general, good practice is to avoid loops/cursors in SQL. Use set based options whenever possible.

Sign up to request clarification or add additional context in comments.

Comments

2

No need for a cursor. Keep it set-based:

insert into planning (resourceid, date)
select resourceid, @SomeDate
from resources
where clientid = @ClientId

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.