[英]Escaping special character when SQL output to variable in shell script
嘗試將包含特殊字符的對象上的SQL查詢的輸出分配給Shell腳本中的變量。
直接在數據庫上運行:
db2 -x 'select count(*) from <SCHEMA>."/BIC/TEST"'
11000
但是,當我在腳本中包含此變量時,我需要使用雙引號,因為我正在使用傳遞到sql中的變量。 使用單引號
Output=$(db2 -x 'select count(*) from ${_SCHEMA}."/BIC/TEST"')
echo -e "$Output"
結果是:
SQL20521N Error occurred processing a conditional compilation directive near
"_". Reason code="7". SQLSTATE=428HV
當我使用雙引號時,我打了:
SQL0104N在“ ount(*)”之后發現意外的標記“'/ BIC / TEST'”
嘗試使用另一組雙引號來轉義雙引號:
db2 -x'從$ {__ SCHEMA}中選擇count(*)。“” / BIC / TEST“”“
但這似乎不適用於腳本。 它適用於沒有特殊字符/要求用引號引起來的表。
任何幫助表示贊賞。
下面的代碼對我來說很好用,請注意轉義的引號。 如果對您失敗,則需要提供有關DB2版本和DB2服務器操作系統平台的更多詳細信息。
#!/bin/ksh
db2 connect to sample
(($? > 0 )) && print "Failed to connect to database" && exit 1
db2 -o- "drop table \"/bin/test\" "
db2 -v "create table \"/bin/test\"(a integer)"
(($? > 0 )) && print "Create table failed" && exit 1
db2 -v "insert into \"/bin/test\"(a) values(1),(2),(3),(4)"
(($? > 0 )) && print "insert rows failed" && exit 1
db2 -v describe table \"/bin/test\"
typeset -i count_rows=$(db2 -x "select count(*) from \"/bin/test\"" )
(($? > 0 )) && print "query count rows failed" && exit 1
print "\nRow count is: ${count_rows}\n"
db2 -o- connect reset
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.