目前我有以下批处理代码来读取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
调用的SQL查询如下
SELECT userId, COUNT (*) AS number
FROM table
WHERE userId = '$(userID)'
GROUP BY userId
ORDER BY userId desc
我正在寻找的是,如果我在文本文件中有用户名列表,它将动态地将 WHERE 语句更改为
WHERE userId = '$(userID1)' OR userId = '$(userID2)' etc....
最佳答案
我没有太多使用 SQL 脚本,所以我不确定返回是否会导致问题,但这会生成您需要的内容。
我在名为 userID.txt 的文件中使用了此输入:
steve,joe,fred,jason,bill,luke
通过这段代码运行它:
@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
在 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
然后在批处理结束时访问:
sqlcmd -S server -d database -U username -P password -i "sqlQuery.sql" -s "," > "\output.csv" -I -W -k
endlocal
关于sql-server - 我如何批量读取用户名列表并在 sql 语句中使用这些用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10032779/