Query performance while using sqlcmd Possible Duplicate:
  Running queries with SQLCMD vs. Running queries with SSMS  




I have a number of scripts that query the data from different tables and consequently update them. I have defined a batch file and run them in sqlcmd command.
It seems that when I run these scripts directly in SQL management studio, they run quicker than when they are called from the batch file.

Is there any reason for this behavior?

Thanks in advance.
Below are what I did to speed up running the scripts with SQLCMD as the outcome of the reading the nice article AmmaR referred me to:

For each script, I added OPTION (RECOMPILE), so SQL would not need to have a query plan, it is compiling and running the script every time. It is especially important when we have used variables in the script. The variables are unknown to SQL until run time. For example in the code below, the randomId is calculated based on what RAND() function returns, so SQL Server has no idea what it would be beforehand. Adding OPTION (RECOMPILE) helped to run this script faster, even though I was running it using SQLCMD.

`   

SET @i = 1

WHILE @i &lt;= @Address_Row_Count 
BEGIN
    SELECT @RandomId = ROUND(((@Upper_Town - @Lower -1) * RAND() + @Lower), 0)

    UPDATE a
    SET 
        a.TownOrCity = 
                    (
                        SELECT 
                            Town   
                        FROM 
                            @TownTble aa 
                        WHERE 
                            aa.Id = @RandomId
                    ) 
    FROM 
        Addresses a
    WHERE
        a.Id = @i
        AND a.PersonId IS NOT NULL OPTION (RECOMPILE)

    SET @i = @i + 1
END `


Thanks for your help!