I want to execute a stored procedure for every row of a table without using cursor or loop. Lets say my table dbo.User contains name for following users:
create table dbo.test_User (
Name varchar(50) )
insert into dbo.test_User
values ('Deepanshu'),('IronMan'),('DoctorStrange')
I created a stored procedure which will only display the name of users (Although my real stored procedure has to do a lot of stuff)
create procedure dbo.usp_TestSP ( @name varchar(50) )
as
BEGIN
select @name
END
Now i want the stored procedure to run for all names like:
EXEC dbo.usp_TestSP 'Deepanshu';
EXEC dbo.usp_TestSP 'IronMan';
EXEC dbo.usp_TestSP 'DoctorStrange';
I created a string variable @Query which will store the t-sql query i want to execute
DECLARE @Query varchar(200);
select @Query=STUFF(
(select 'dbo.usp_TestSP '''+Name+''';'
from dbo.test_user
FOR XML PATH('')
),1,0,''
)
EXEC @Query
When i try to execute this @Query it gives me an error saying:
Could not find server 'dbo' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.
How can i execute the stored procedure for all the names using the string variable @Query?