SQLCMD – Resolving Issues with -q and Quotation Marks

indexsql serversql-server-2008-r2sqlcmd

I have a SQL Server 2008 R2 Express edition. Because it is only an Express edition I don't have a SQL Server Agent for automation of tasks.

So I tried to do something with command line program sqlcmd.

I try to execute this command:

use DB; EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', 80)";

If I do this in SQL Server Management Studio everything works fine. But if I try to execute this via sqlcmd it doesn't work.

sqlcmd -S .\INSTANCE -Q "use DB; EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', 80)";" -o C:\FOLDER\LOG_DB_REINDEX.txt

I think this is because of the quotation marks. I also tried to use ` and ' but I didn't get it to work…

How can I resolve this issue?

Best Answer

Try to use this. ;-)

use DB; EXEC sp_MSforeachtable @command1=N'print ''?'' DBCC DBREINDEX (''?'', '' '', 80) ';

Double quotation marks will escape the following quotation mark.

Here an example of sqlcmd:

sqlcmd -S YOURSERVER -Q "use net_temp_test; EXEC sp_MSforeachtable @command1=N'print ''?''';"