mho*_*321 4 sql-server loops batch-file sqlcmd
目前我有以下批处理代码来读取1个用户名,并在sql中使用它
@echo on
cls
set userID=
for /F %%i in (UserID.txt) do set userID=%userID% %%i
sqlcmd -S server -d database -U username -P password -v userID=%userID%
-i "sqlQuery.sql" -s "," > "\output.csv" -I -W -k
Run Code Online (Sandbox Code Playgroud)
调用的SQL查询如下所示
SELECT userId, COUNT (*) AS number
FROM table
WHERE userId = '$(userID)'
GROUP BY userId
ORDER BY userId desc
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是,如果我在文本文件中有一个用户名列表,它将动态更改WHERE语句
WHERE userId = '$(userID1)' OR userId = '$(userID2)' etc....
Run Code Online (Sandbox Code Playgroud)
我没有使用SQL脚本,所以我不确定返回是否会导致问题,但这将产生你需要的东西.
我在名为userID.txt的文件中使用了此输入:
steve,joe,fred,jason,bill,luke
Run Code Online (Sandbox Code Playgroud)
通过这段代码运行它:
@echo off
setlocal enabledelayedexpansion
set count=0
for /F "tokens=* delims=," %%G in (userID.txt) do call :loop %%G
:loop
if "%1"=="" goto :endloop
set /a count+=1
set userid%count%=%1
SHIFT
goto :loop
:endloop
set totalusers=%count%
set /a totalusers-=1
echo SELECT userId, COUNT (*) AS number FROM table WHERE ( > sqlQuery.sql
set count=0
:where_gen_loop
set /a count+=1
if !count! gtr !totalusers! goto endwhere_gen_loop
echo userId = '$(!userid%count%!)' OR>> sqlQuery.sql
goto where_gen_loop
:endwhere_gen_loop
echo userId = '$(!userid%count%!)'>> sqlQuery.sql
echo ) >> sqlQuery.sql
echo GROUP BY userId ORDER BY userID desc >> sqlQuery.sql
Run Code Online (Sandbox Code Playgroud)
在sqlQuery.sql中生成此输出:
SELECT userId, COUNT (*) AS number FROM table WHERE (
userId = '$(steve)' OR
userId = '$(joe)' OR
userId = '$(fred)' OR
userId = '$(jason)' OR
userId = '$(bill)' OR
userId = '$(luke)'
)
GROUP BY userId ORDER BY userID desc
Run Code Online (Sandbox Code Playgroud)
然后在批处理结束时访问:
sqlcmd -S server -d database -U username -P password -i "sqlQuery.sql" -s "," > "\output.csv" -I -W -k
endlocal
Run Code Online (Sandbox Code Playgroud)