Read values from comma delimited file and generate sql

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
victorlui
Posts: 3
Joined: 13 Dec 2013 02:43

Read values from comma delimited file and generate sql

#1 Post by victorlui » 13 Dec 2013 02:51

I have a comma delimited input file param.txt:
A,1
B,2
C,3
......

I would like to create a batch file that:
1. read every lines of param.txt
2. and generate the sql like below for each line

line1.sql:
select * from table1
where col1 = 'A'
and col2 = '1'
;

line2.sql:
select * from table1
where col1 = 'B'
and col2 = '2'
;

line3.sql:
select * from table1
where col1 = 'C'
and col2 = '3'
;

......

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Read values from comma delimited file and generate sql

#2 Post by foxidrive » 13 Dec 2013 04:04

Do you want a separate file for each line?


foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Read values from comma delimited file and generate sql

#4 Post by foxidrive » 13 Dec 2013 09:34

Code: Select all

@echo off
setlocal enabledelayedexpansion
set "c=0"
for /f "tokens=1,2 delims=," %%a in (params.txt) do (
set /a c=c+1
>>"line-!c!.sql" echo select * from table1
>>"line-!c!.sql" echo where col1 = '%%a'
>>"line-!c!.sql" echo and col2 = '%%b'
>>"line-!c!.sql" echo ;
)

victorlui
Posts: 3
Joined: 13 Dec 2013 02:43

Re: Read values from comma delimited file and generate sql

#5 Post by victorlui » 14 Dec 2013 22:46

The result is line-c+1.sql having the following content:

select * from table1
where col1 = 'A'
and col2 = '1'
;
select * from table1
where col1 = 'B'
and col2 = '2'
;
select * from table1
where col1 = 'C'
and col2 = '3'
;

can I have the 3 files instead?

# line1.sql
select * from table1
where col1 = 'A'
and col2 = '1'
;

# line2.sql
select * from table1
where col1 = 'B'
and col2 = '2'
;

# line3.sql
select * from table1
where col1 = 'C'
and col2 = '3'
;

ShadowThief
Expert
Posts: 1167
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: Read values from comma delimited file and generate sql

#6 Post by ShadowThief » 14 Dec 2013 23:14

Code: Select all

@echo off
setlocal enabledelayedexpansion

set counter=0
for /f "tokens=1,2 delims=," %%A in (param.txt) do (
   set /a counter=!counter!+1
   echo select * from table1>>line!counter!.sql
   echo where col1 = '%%A'>>line!counter!.sql
   echo and col2 = '%%B'>>line!counter!.sql
   echo ;>>line!counter!.sql
)


EDIT: Oh look at me, putting extra spaces in output where they don't belong.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Read values from comma delimited file and generate sql

#7 Post by foxidrive » 15 Dec 2013 03:15

victorlui wrote:The result is line-c+1.sql having the following content:

can I have the 3 files instead?


I forgot /a in the set command. It's fixed - try the code in that post again.

Post Reply