0

I want to run a stored procedure on each ID return by a SELECT query. Is there a simple way to do something like:

FOREACH (SELECT ID FROM myTABLE WHERE myName='bob') AS id
BEGIN
    EXEC @return_value = [dbo].[spMYPROC]
         @PARAM1 = id
         @PARAM2 = 0
END
11
  • 4
    Instead of trying to do some sort of looping on a table, why not pass in the ID's to the stored procedure? Commented Jan 24, 2014 at 21:38
  • 2
    Agreed with @TTeeple - change the stored procedure to handle all of the rows in myTABLE instead of a singleton procedure that you call N times. There is significant overhead in looping at all, never mind calling a stored procedure every time. SQL Server is optimized to work on sets. You want to do something in your procedure to every row in a set, but you really should change it to just do whatever that is to all the rows at once. If you show the body of your procedure we can help you do that. Commented Jan 24, 2014 at 21:41
  • Check out this post, it does something very similar: Run a Stored Procedure multiple times dynamicly Commented Jan 24, 2014 at 21:42
  • I do think a set based approach would serve you better. Commented Jan 24, 2014 at 21:43
  • 1
    The T-SQL command for looping is while, not foreach (see technet.microsoft.com/en-us/library/ms174290.aspx). If your stored procedure is designed to take one id, I wouldn't recommend changing it to take many ids, unless that is a reasonable requirement for the API. Commented Jan 24, 2014 at 21:43

3 Answers 3

1

Since I just happened to answer a very similar question yesterday, I have this code handy. As others have stated, it may not be the best approach, but still it's nice to learn how to use a while loop anyway.

Assuming a table named "Customer"

declare @Id int

select @Id = MIN(Id)
from Customer c


while(select COUNT(1)
      from Customer c
      where c.Id >= @Id) > 0
    begin

        --run your sproc right here

        select @Id = MIN(Id)
        from Customer c
        where c.Id > @Id


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

1 Comment

interesting one served my purpose
0
DECLARE @ID INT, @return_value INT

DECLARE c CURSOR FOR
SELECT
    ID
FROM myTABLE
WHERE myName = 'bob'

OPEN c; FETCH NEXT FROM c INTO @ID

WHILE @@FETCH_STATUS = 0
BEGIN
     EXEC @return_value = [dbo].[spMYPROC]
         @PARAM1 = @ID,
         @PARAM2 = 0

    FETCH NEXT FROM c INTO @ID
END

CLOSE c; DEALLOCATE c;

Comments

0

You have two option here

Option 1 Using Split Function

Pass a comma deliminated list of IDs and use a Split function Inside your Procedure to make split these values and do whatever you want to do with it.

To Make it work you will need two thing

1) Create a Function which accepts a Comma Deliminated string and split them.

2) Modify you Store Procedure and add this function in there in a way that passed parameter is passed to the function inside that store procedure and that function split the values before passing it onto your store Procedure .

Create this function 1st

Function Definition

CREATE FUNCTION [dbo].[FnSplit]
(
@List nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table (Id int identity(1,1), Value nvarchar(100))
AS
BEGIN

WHILE(Charindex(@SplitOn,@List)>0)

  BEGIN


        INSERT INTO @RtnValue (value)

        SELECT VALUE = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))

        SET @List = SUBSTRING(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))

  END


INSERT INTO @RtnValue (Value)

SELECT VALUE = ltrim(rtrim(@List))

RETURN

END

Modify you strored Procedure something like this

Stored Procedure

ALTER Procedure  [dbo].[spMYPROC] (@Param1 VARCHAR(1000)= NULL)
AS
BEGIN

        SELECT * FROM TableName
        where ColumnNAME  IN (SELECT Value FROM dbo.FnSplit(@Param1,','))

END
GO

Option 2 Table Type Parameter

Create a Table Type and alter your proc to accept a Table Type Parameter and do whatever you want to do with them values inside your proc.

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE 
 (
    Value int 
  )
 GO

Stored Procedure to Accept That Type Param

 ALTER PROCEDURE [dbo].[spMYPROC]  
 @TableParam TYPENAME READONLY
 AS 
   BEGIN
    SET NOCOUNT ON;
  --Temp table to store passed Id values
  declare @tmp_values table (value INT );   

   --Insert passed values to a table variable inside the proc

   INSERT INTO @tmp_values (value)
   SELECT Value FROM @TableParam

    /* Do your stuff here whatever you want to do with Ids */

END

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE

 INSERT INTO @Table                --<-- Populating the variable 
 SELECT ID FROM myTABLE WHERE myName='bob'

EXECUTE [dbo].[spMYPROC]  @Table   --<-- Stored Procedure Executed 

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.