Hi @Priya Jha
When you EXEC with a string, the command is carried out in a new session, so variables cannot be used pass arguments or get results. However, you could create a temporary table and use this table inside the dynamic statement, like this:
CREATE TABLE #createindex (id int identity(1,1), indexscript varchar(max));
INSERT INTO #createindex VALUES ('Create Index Index1 on table1 (Col1)')
INSERT INTO #createindex VALUES ('Create Index Index2 on table1 (Col2)')
DECLARE @SQL VARCHAR(max)
SET @SQL='
declare @countindex int
declare @count int
set @countindex = (select count(1) from #createindex)
set @count = 1
declare @indexscript varchar(max)
while (@count <=@countindex)
begin
set @indexscript = (select indexscript from #createindex where id =@count)
exec (@indexscript)
set @count =@count+1
end'
PRINT @SQL
EXEC (@SQL)
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.