2017-10-19 59 views
0

我想在sql服務器查詢where子句中使用sqsh變量,但無法使其工作。以下是對我所面臨問題的簡單模擬。有人可以幫我解決這個在sqsh腳本中使用變量不工作,而在sql服務器查詢

可正常工作

select * from information_schema.tables where table_name = 'PHONES'; 

但下面不會工作

\set tableName=PHONES; 

select * from information_schema.tables where table_name = $tableName; 
    Error Message:: Invalid column name 'PHONES' 

select * from information_schema.tables where table_name = '$tableName'; 
    No rows are returned as it searches for a table $tableName 

select * from information_schema.tables where table_name = "$tableName"; 
    Error Message:: Invalid column name 'PHONES'. 

回答

0

爲了解釋這裏發生了什麼,你應該看看SQL緩衝區即在可變擴展後發送到服務器。爲了做到這一點,你應該跳過';'快捷方式,並在下一行提供'\ go -e'(不包括引號)。請注意,如果發生錯誤,這可能不會顯示SQL緩衝區。

第一行會展開:

select * from information_schema.tables where table_name = PHONES 

這裏PHONES被解釋爲在表中的列名,但由於該列名不存在,SQL服務器顯示錯誤信息。

第二行將擴展爲:

select * from information_schema.tables where table_name = '$tableName' 

由於單引號,變量不被SQSH膨脹並原樣,因此空結果集發送到服務器。

第三行會展開:

select * from information_schema.tables where table_name = "PHONES" 

這看起來更像是一個字符串搜索參數,但由於事實QUOTED_IDENTIFIER選項可能是在默認情況下,SQL服務器仍在尋找列命名爲PHONES。

爲了解決這個問題,您應該提供單引號,但仍然希望sqsh擴展變量。您可以通過轉義單引號來實現此目的:

select * from information_schema.tables where table_name = \\'$tableName\\'; 

希望這有助於您。

+0

像冠軍一樣工作。 – kishore

相關問題