• aakash214 (3/7/2013)


    Hi,

    I have a procedure which has a code something like

    My SP is dynamic something like

    WHILE(@i <= @max-2)

    BEGIN

    SELECT @db_name = db_name, @db_server_name = db_server_name from #dbs where id = @i

    SET @SQL = 'EXEC '+@db_server_name+'.'+@db_name+'.dbo.SP_NAME '+@param1+','+@param2

    INSERT into #temp(...)

    EXEC (@SQL)

    END

    When I execute SP without insert statement (without insert into #temp(..)) SP returns in 2 seconds. But, when data is inserted into temp table it takes 7-8 seconds.

    Only 36 records are returned.

    I tried using Table Variables but it doesn't help. Even tried Permanent table but still no use.

    My question is why is INSERT.. EXEC.. taking too long time than just an EXEC .. And is there any better option than that. I tried googling out to find solution and came across various posts saying INSERT.. EXEC.. has performance impact. Few pointed out to Linked Server being slow. But, I was not able to find any solution.

    Thanks for your help. Will be happy to provide any other information requried.

    Just a guess, but it could be because SQL Server has to run the insert in a distributed transact and it is taking a little extra time for that to be accomplished. I don't have a distributed environment in which I can test this theory.