有一个名为SchemaCrawler的项目可用于比较 2 个不同的数据库。我使用批处理文件编写了脚本并且效果很好。
但是,从批处理中执行 MSSQL 查询的最佳方法是这样的。这演示了使用胡萝卜字符进行续行、延迟扩展变量、将 SQL 结果输出到文件以及从文件中读取变量:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: batch file for sql query
SET HOST=qa071.xyz.com
SET FIELDVAL=PRE%%
SET DBNAME=MYDB
SET USER=username
SET PASS=Passw3rd1
:: Do query
SET SQLSTRING=SELECT PARM_ID, PARM_NAME, PARM_VALUE^
FROM CONFIG^
WHERE PARM_NAME LIKE '%FIELDVAL%'
ECHO !SQLSTRING!
ECHO.
ECHO sqlcmd.exe -b -S !HOST! -d !DBNAME! -Q "!SQLSTRING!" -W -U !USER! -P !PASS!
sqlcmd.exe -b -S !HOST! -d !DBNAME! -Q "!SQLSTRING!" -W -U !USER! -P !PASS!
:: Count results and display count
SET SQLSTRING=SELECT COUNT(*)^
FROM TB_CONFIG^
WHERE PARM_NAME LIKE '%FIELDVAL%'
ECHO !SQLSTRING!
ECHO.
ECHO sqlcmd.exe -b -S !HOST! -d !DBNAME! -Q "!SQLSTRING!" -W -U !USER! -P !PASS! -h -1
sqlcmd.exe -b -S !HOST! -d !DBNAME! -Q "!SQLSTRING!" -W -U !USER!^
-P !PASS! -h -1> count.txt
SET /P THECOUNT=<count.txt
ECHO The count is: %THECOUNT%
ECHO.
DEL /Q count.txt
ECHO Query is done. Hit any key to close this window....
pause>nul