检查逗号分隔列表是否为空时出错(空白)

Error when checking if a comma separated list is empty (blank)

我得到一个逗号分隔的列表,其中包含数据库中某个字段的值。这个列表有时是空白的。我需要检查列表是否为空,然后做一些事情。如果列表不为空,则执行其他操作。

问题是我在检查列表是否为空时遇到错误。这是代码。请注意,我在代码的开头模拟了值来自数据库。

这是我之前尝试过的方法:如果 VendorStores 的列表为空(空白),请执行一项操作。否则采取另一个行动。当 VendorStores 有多个值(逗号分隔)并将其与空白进行比较时,我遇到了错误。所以现在我正在尝试计算这些值并使用该计数来做出决定。但我遇到了同样的问题。当 VendorStores 为空时,for 循环仍然认为它有 2 个值 - 1) ",=" 2) ""。不知道为什么会这样。

:: Intention of the script is as follows:
:: If VendorStores list is blank, take one action
:: If VendorStores list has values, take another action

@echo off
:: Set values for VendorStores
:: set vendorstores=123,234,345
:: Set VendorStores to blank
set vendorstores=
echo list = "%vendorstores%"
:: Remove any blank spaces from VendorStores
set vendorstores=%vendorstores: =%
set /a c=0
echo c=%c%
SETLOCAL EnableDelayedExpansion
for %%a in ("%vendorstores:,=" "%") do (
    if [%%a] NEQ [] (
        set /a c=c + 1
        echo VendorStore is %%a
    )
    echo c=!c!
)
echo c=!c!
if [!c!] EQU [0] (
    echo c is equal to Zero
) else (
    echo c is greater than Zero
)
echo c=!c!
endlocal

错误的结果来自FOR命令行:

for %%a in ("%vendorstores:,=" "%") do (

在此命令行上方插入一行 echo on 并在 FOR 的右括号后插入一行 @echo off 可以很容易地看出为什么失败。

正确的命令行应该是:

for %%a in (%vendorstores%) do (

但是在环境变量 vendorstores 根本没有定义的情况下,使用这个 FOR 循环是不好的。

这是一个名为 Test.bat:

的批处理文件的简化示例
@echo off
set "VendorStores=%~1"
if not defined VendorStores  goto EmptyList
set "VendorStores=%VendorStores: =%"
if not defined VendorStores  goto EmptyList
if "%VendorStores:,=%" == "" goto EmptyList
echo List is: %VendorStores%
goto :EOF

:EmptyList
echo The list is empty.

可以在命令提示符 window 中执行此批处理文件,如下所示:

Test.bat
Test.bat ,,,,
Test.bat ", , , ,"
Test.bat " 123, 234, 345 "
Test.bat "376,983,305,253"

这 5 个批处理文件执行的输出是预期输出的 5 倍。

:: Intention of the script is as follows:
:: If VendorStores list is blank, take one action
:: If VendorStores list has values, take another action

@echo off
:: Set values for VendorStores
:: set vendorstores=123,234,345
:: Set VendorStores to blank
set vendorstores=
echo list = "%vendorstores%"
:: Remove any blank spaces from VendorStores
set vendorstores=%vendorstores: =%

::::If there is any value in StoreCSV, then remove any comma delimiters from it as the "if" statement does not like commas
if defined vendorstores (
set "vendorstores=%vendorstores:,=%"
)

SETLOCAL EnableDelayedExpansion

if [%vendorstores%] EQU [] (
    echo VendorStores is blank
) else (
    echo VendorStores has one or more values
)

endlocal

还有一个选项:

@Echo Off
Set "VendorStores="
For /F "EOL=, Delims=, " %%A In ("%~1") Do Set "VendorStores=%%A"
If Not Defined VendorStores (Echo VendorStores is blank
) Else Echo VendorStores has one or more values