2013-02-07 122 views
0

這是我的問題。我有一組SQL數據庫查詢,我使用shell腳本和擴展名爲.sql的相應批處理文件觸發。我的一些查詢需要一些手動用戶輸入(根據請求),我沒有在我的腳本中實現。在MYSQL中接受用戶輸入? Shell腳本/批處理文件

截至目前,我採取在用戶輸入作爲通過殼腳本日期:

echo "Please specify the date in yyyy-mm-dd format: 'input;" 
read input 
mysql -u user -ppass < batch_file.sql 

我想可變$input傳遞給批處理文件。

與正在執行的SQL查詢批處理文件看起來是這樣的:

select count(*) as count from subscriptions 
where date_add(optin_date, interval 1 year) between "$input" 
and date(curdate()) 
and active = 1 
and stype = "domain"; 

哪裏"$input"從shell腳本傳下來的變量。

任何想法將欣賞,謝謝。在腳本中使用這裏-DOC

回答

1

嘗試這樣做:

#!/bin/sh 

echo "Please specify the date in yyyy-mm-dd format: 'input;" 
read input 
mysql -u user -ppass <<EOF 
select count(*) as count from subscriptions 
where date_add(optin_date, interval 1 year) between "$input" 
and date(curdatE()) 
and active = 1 
and stype = "domain"; 
EOF 

另一種解決方法,如果你不能使用任何原因,第一個解決方案:

echo "Please specify the date in yyyy-mm-dd format: 'input;" 
read input 
sed -i "s/\"\$input\"/$input/g" batch_file.sql 
mysql -u user -ppass < batch_file.sql 

更好地利用的東西如%%PATTERN%%而不是$input在SQL文件中進行替換,如果您更喜歡第二種解決方案。

+0

第一個解決方案只允許一次運行一個命令,因此是批處理文件。 第二種解決方案很有意義,但它沒有檢測到變量。 – KamilS

+0

您可以使用'&'(fork)在後臺運行here-docs,因此您可以運行SQL批處理的N個實例。 –

+0

此外,只需檢查,第一個解決方案不起作用。 '$ input'變量沒有被識別。 – KamilS