User input multple values assigned to 1 variable BATCH

只谈情不闲聊 提交于 2020-01-06 07:07:16

问题


MY BATCH FILE LOOKS LIKE THIS

ECHO OFF

SET /P colu= Enter column name:
SET /P sn= Enter ID (Press enter when finished): 

 if %sn%={ENTER}
  GOTO START

  :START
sqlcmd -U USER -P PWORD -S  SERVER -d DBNAME-i sqlSCRIPT.sql -o LOG.txt 
-v delete=colu d_id=sn

I want the user to be able to enter multiple ids in a single line. Those ID's will be deleted from the DB using the sqlScript.sql however this code is not allowing me to enter multple ids.

It is looking at the values I enter as 1 whole value.

For an example if I enter 1,2,3 (as separate values) it sees it as '1,2,3' as 1 whole value.


回答1:


There are several issues in your code:

  • the variables colu and sn should be cleared at the beginning to avoid using some former value;
  • the if clause has no sense, and the syntax was wrong;
  • to use values of a variable, you need to expand them like %colu%;
  • to use one value after another, use a for loop;
  • there is a line-break in the middle of the sqlcmd command line;

The following should do what you want:

@ECHO OFF

SET colu=
SET sn=
SET /P colu= Enter column name:
SET /P sn= Enter ID (Press enter when finished): 

FOR %%I IN (%sn%) DO (
  sqlcmd -U USER -P PWORD -S SERVER -d DBNAME-i sqlSCRIPT.sql -o LOG.txt -v delete=%colu% d_id=%%I
)



回答2:


Use the FOR loop an set set a comma(,) as the delimiter then use another FOR loop to process the SQL commands for each i.d



来源:https://stackoverflow.com/questions/33041407/user-input-multple-values-assigned-to-1-variable-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!