Ask Your Question
1

How can a stored procedure be executed in a loop for every record within a user-defined table type parameter by calling it within another stored procedure?

asked 2023-07-08 05:46:39 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-08 06:00:01 +0000

bukephalos gravatar image

One approach to executing a stored procedure in a loop for every record within a user-defined table type parameter is to use a cursor. Here is an example of how this can be done:

  1. Define the user-defined table type:
CREATE TYPE MyTableType AS TABLE (
   ID int,
   Name varchar(50)
);
  1. Define the stored procedure that takes the user-defined table type parameter:
CREATE PROCEDURE MyProcedure
   @TableType MyTableType READONLY
AS
BEGIN
   DECLARE @ID int
   DECLARE @Name varchar(50)

   DECLARE cur CURSOR LOCAL FOR
      SELECT ID, Name
      FROM @TableType

   OPEN cur

   FETCH NEXT FROM cur INTO @ID, @Name

   WHILE @@FETCH_STATUS = 0
   BEGIN
      -- Execute the stored procedure for each record in the table type
      EXEC MyOtherProcedure @ID, @Name

      FETCH NEXT FROM cur INTO @ID, @Name
   END

   CLOSE cur
   DEALLOCATE cur
END
  1. Define the stored procedure that will be executed for each record in the table type:
CREATE PROCEDURE MyOtherProcedure
   @ID int,
   @Name varchar(50)
AS
BEGIN
   -- Do something with the ID and Name values
   PRINT @ID
   PRINT @Name
END
  1. Call the main stored procedure with a table variable that contains the data:
DECLARE @MyTable MyTableType

INSERT INTO @MyTable (ID, Name)
VALUES (1, 'John'), (2, 'Jane'), (3, 'Bob')

EXEC MyProcedure @MyTable

This will execute the MyOtherProcedure stored procedure for each record in the @MyTable variable.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-08 05:46:39 +0000

Seen: 8 times

Last updated: Jul 08 '23