在sqsh脚本中使用变量不工作,而在sql服务器查询
问题描述:
我想在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'.
答
为了解释这里发生了什么,你应该看看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\\';
希望这有助于您。
像冠军一样工作。 – kishore