将参数传递给文件中的 SQL 查询

Pass parameter to SQL query in a file

我有以下查询(称之为 queryA):

Select * from TableA where FieldA in ('foo', 'bar')

我想编写一个(shell?)脚本文件,类似于:

execute queryA take parameter values from ParamFileA write output to OutputFileA

ParamFileA 将包含 ('foo', 'bar')

可能吗?这适用于 SQL 服务器。

制作一个包含以下内容的 .bat 文件(详细信息请阅读 REM 注释):

REM This script expects these parameters: Path of file with query to run, path of file with parameters, path of file to save output in.
set SQLFILE=%1
set PARAMFILE=%2
SET OUTPUTFILE=%3

SET TEMPFILEPATH=C:\Temp\tempsqlstatementt.sql

REM Combine SQL command and parameters into one temporary file.
copy /B %SQLFILE% + %PARAMFILE% %TEMPFILEPATH%

REM Execute combined SQL command and write to specified output
sqlcmd -S myServer\instanceName -i C:\Temp\tempsqlstatementt.sql -o %OUTPUTFILE%

REM Cleanup the temp file.
DEL %TEMPFILEPATH% /F /Q

你可以这样调用这个bat文件:

ExecuteWithParams QueryFile ParamFile OutputFile

又来了,但我输入了实际的文件路径:

C:\Users\You\>ExecuteWithParams.bat QueryFile.sql ParamFile.sql OutputFile.txt

此外,如果 sqlcmd 不在 path 上,您必须将 sqlcmd 的路径放入 bat 文件中。