Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop through query results

DECLARE @files TABLE (DocumentID Varchar(50))

INSERT INTO @files (DocumentID)
SELECT DISTINCT D.DocumentID
FROM Documents D
WHERE D.DocumentID IN ('637542', '655437', '655900') --example for debugging

-- loop
DECLARE @i INT = 1
DECLARE @rowCount INT = (SELECT COUNT(*) FROM @files)

WHILE @i <= @rowCount
BEGIN
   DECLARE @id Varchar(50) = (SELECT DocumentID FROM @files WHERE ROW_NUMBER() = @i)
   EXEC dbo.bom @docuid=@id
   SET @i = @i + 1
END

This code gives me the following errors:

Msg 10753, Level 15, State 3, Line 19
The function 'ROW_NUMBER' must have an OVER clause.
Msg 137, Level 15, State 2, Line 20
Must declare the scalar variable "@id".

How can I declare an OVER clause if I’m using @i there and what does exactly the scalar variable message mean?

As the procdeure name might suggest, it prints a bill of materials for the selected docid. I’d like to print boms of multiple files to one dataset.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When executing the procedure once, it looks like this:

docuid description etc
637542 value a value x

What I need, looks like this:

docuid description etc
637542 value a value x
355437 value b value y
655900 value c value z

>Solution :

DECLARE @InDocumentID VARCHAR(50);
SET @InDocumentID='';
DECLARE cCursor CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
   SELECT DISTINCT D.DocumentID
   FROM Documents AS D
   WHERE D.DocumentID IN ('637542', '655437', '655900');
OPEN cCursor;
FETCH NEXT FROM cCursor INTO @InDocumentID;
WHILE @@FETCH_STATUS=0
BEGIN
  EXEC dbo.bom @docuid=@InDocumentID;
  FETCH NEXT FROM cCursor INTO @InDocumentID;
END
CLOSE cCursor;
DEALLOCATE cCursor;

I would try standard cursor approach

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading