sql-server - 我如何批量读取用户名列表并在 sql 语句中使用这些用户名?

标签 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

调用的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/

相关文章:

sql-server - t-sql 计算文本列中的唯一单词

java - JDBC MS SQL Server Kerberos 身份验证

python - 扁平化嵌套循环/降低复杂性 - 互补对计数算法

excel - VBA Excel,循环变量

windows - “RD”命令在成功或失败时不返回 '0' 或 '1' 作为错误级别

sql - WHERE 子句中是否可以有 CASE WHEN THEN SELECT

java - 使用 JDBC 语句执行查询时出现 NullPointerException

javascript - 如何在 React 中使用循环显示数据?

windows - 如果 Windows 中不存在目录,则使用 for 循环和列表创建目录

batch-file - 为什么 forfiles 吞下命令的第一个参数?