I have to use a Stored Procedure - that I cannot change/modify. While it is a bit complicated, it can be simplified to be a SELECT
statement i.e. with no RETURN
or OUTPUT
parameter. For the purpose of this discussion assume it to be something like:
SELECT [URL] as imgPath
FROM [mydatasource].[dbo].[DigitalContent]
I need to execute this Stored Procedure passing in the Row ID (SKU) of each row in a Table. I use a cursor for this as below:
DECLARE @sku varchar(100)
DECLARE @imgPath varchar(500)
DECLARE c CURSOR FOR
SELECT [SKU]
FROM [mydatasource].[dbo].[PROD_TABLE]
OPEN c
FETCH NEXT FROM c INTO @sku
WHILE @@FETCH_STATUS = 0 BEGIN
EXEC @imgPath = [mydatasource].[dbo].[getImage] @sku
--UPDATE PROD_TABLE SET ImgPath=@imgPath WHERE SKU=@sku
SELECT @imgPath AS ImgPath
FETCH NEXT FROM c INTO @sku
END
CLOSE c
DEALLOCATE c
Unfortunately, the return value @imgPath
comes back as 0
i.e. success. This results in 0
s being inserted into my PROD_TABLE
or dumped on the Console. However, as the getImage
Stored Procedure executes, it dumps the correct values of imgPath
to the console.
How do I get this correct value (i.e. the result of the SELECT
in the Stored Procedure) in the Loop above, so that I can correctly update my PROD_TABLE
?
Answer
Thanks to RBarryYoung suggestion, my final code looks like:
DECLARE @sku varchar(100)
DECLARE @imgPath varchar(500)
DECLARE c CURSOR FOR
SELECT [SKU]
FROM [mydatasource].[dbo].[PROD_TABLE]
OPEN c
FETCH NEXT FROM c INTO @sku
WHILE @@FETCH_STATUS = 0 BEGIN
CREATE TABLE #OutData ( imgPath varchar(500) )
INSERT INTO #OutData EXEC [mydatasource].[dbo].[getImage] @sku
--UPDATE PROD_TABLE SET ImgPath=(SELECT * FROM #OutData) WHERE SKU=@sku
SELECT * FROM #OutData
DROP TABLE #OutData
FETCH NEXT FROM c INTO @sku
END
CLOSE c
DEALLOCATE c
The performance may not be the best, but at least it works :-).