sql-servert-sqlosql

@@ROWCOUNT in OSQL returns different result than in TSQL


I am experiencing some strange behavior with OSQL, and would appreciate any help.

I have a batch file that will copy a database field from one column to another. Here is a sample script:

SET NOCOUNT ON; 
UPDATE Table1 SET Table1.EmailAddress = Table2.GenericField FROM Table1
INNER JOIN Table2 ON Table1.ID = Table2.ID WHERE GenericField LIKE '%@%.%' 
   AND EmailAddress IS NULL;
SELECT @@ROWCOUNT;

Assuming all the EmailAddress fields are NOT NULL anymore, I would expect the update statement to return a @@ROWCOUNT of 0.

Running the above query in Query Analyzer gives me 0 for the @@ROWCOUNT. That's good.

Test.Sql contains the exact same SQL statement as above. If I use the following OSQL statement, I also get a 0 for the @@ROWCOUNT:

osql.exe -D TestConn -U UserID -P pwd -s , -h-1 -w 100 -n ^
    -i "C:\Scripts\Test.sql"

If I have the SQL statement in the batch file instead of a SQL file, I get a @@ROWCOUNT of 2:

osql.exe -D TestConn -U UserID -P pwd -s , -h-1 -w 100 -n -Q ^
  "SET NOCOUNT ON; 
   UPDATE Table1 SET Table1.EmailAddress = Table2.GenericField FROM Table1
   INNER JOIN Table2 ON Table1.ID = Table2.ID WHERE GenericField LIKE '%@%.%' 
      AND EmailAddress IS NULL;
   SELECT @@ROWCOUNT;" 

Do I have a switch set wrong for example 3? Why would I suddenly get a @@ROWCOUNT of 2 instead of 0?

The first time I ran the script, I got a @@ROWCOUNT of 5, when only three records were updated.


Solution

  • Batch files expand % to a variable. You can escape it by using double %%s:

    WHERE GenericField LIKE '%%@%%.%%'