1

I'm pretty new to SQL...looking for a simple solution. I have a query where I declare a list of foreign keys, like this:

DECLARE @CustomerFkList table (Fk int);

BEGIN
INSERT @CustomerFkList (Fk) VALUES (12345), (67890), (65432)
END

Later on in the query I want to INSERT one record into a specific table for each of the values in my list, where the foreign key value goes into a foreign key field. What's the best approach for this?

Here is the full code - what I have so far. I know that the last two lines are wrong:

USE CustomerDatabase;
DECLARE @CustomerFkList table (Fk int);

BEGIN
INSERT @CustomerFkList (Fk) VALUES (x), (x), (x), (etc.)
END

BEGIN
UPDATE CustomerLifeCycleStatus SET EndDate=GETDATE() 
    WHERE (CustomerFk IN (SELECT Fk FROM @CustomerFkList)
            AND LifeCycleStatus = 'Active' 
            AND EndDate IS NULL)
END 

/* ------- below is what I need to iterate through ---------- */
INSERT INTO CustomerLifeCycleStatus (CustomerFk, LifeCycleStatus, StartDate) 
    VALUES (@CustomerFkList, 'Retired', GETDATE());

Help please? (I'm using SQL-Server 2008 R2, Microsoft SQL Server Management Studio)

1 Answer 1

2

No need to iterate, just insert it all with a single statement:

INSERT INTO CustomerLifeCycleStatus (CustomerFk, LifeCycleStatus, StartDate) 
SELECT FK, 'Retired', GETDATE()
FROM @CustomerFKList
Sign up to request clarification or add additional context in comments.

1 Comment

Wow - that's beautifully simple. Thank you!

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.