SQL is a set based language. Very very rarely do you need to use a loop.
Consider changing the stored procedure to get the data it requires by joining to the
table
instead.
If the "some logic" is not trying to update a table, just return a value, then create a Function instead and call it as part of the select e.g.
select [Id], [name], MyFunction([name]) as Result from [table]
I wrote an article some time ago about alternatives to loops, but it also includes some examples of loops if you absolutely have to use one - see
Processing Loops in SQL Server[
^]
EDIT after OP comment
---------------------
Quote:
what my stored procedure does
is inserting into two tables using the same Id and delete from 2 other tables using the same Id
create procedure doLogic
@Id int
Insert into table1(Id) values @Id
Insert into table2(Id) values @Id
delete from table3 where Id = @Id
delete from table4 where Id = @Id
Return 0
Here is some sample data that matches to the tables you have used in your examples
create table #table (id int identity(1,1), [name] varchar(50))
insert into #table ([name]) values
('name A'),('name B'),('name C'),('name D')
create table #table1 (id int)
create table #table2 (id int)
create table #table3 (id int)
insert into #table3 (id) values (3),(7)
create table #table4 (id int)
insert into #table4 (id) values (1),(4),(8),(9)
Using that sample data, in the stored procedure, I could replace
Insert into table1(Id) values @Id
Insert into table2(Id) values @Id
that does the insert one by one (or RBAR = Row By Agonising Row - can't remember who says that. I'll look it up later), with two lines that will do the entire table
at once i.e.
insert into #table1 select [id] from #table
insert into #table2 select [id] from #table
I can use a couple of alternative ideas for replacing
delete from table3 where Id = @Id
delete from table4 where Id = @Id
The first one is trivial and just deletes anything that matches ...
delete from #table3 where [id] in (select id from #table)
This second one is essentially exactly the same but I've included it to try to show that you can make the sub-query as complex as you like
delete from #table4 where [id] in (select #table4.id from #table inner join #table4 on #table.id = #table4.id)
Yous also mentioned
Quote:
and can u explain the function example you mentioned more? how to replace it with the select that returns all records? that i need to pass to the stored procedure?
A user-function cannot amend records it can only return values so it's not appropriate now that I know what you are trying to do in your stored procedure. Leave that for another time