在 sql 服务器中查询时,在 sqsh 脚本中使用变量不起作用

Using a variable in a sqsh script is not working while querying in sql server

我试图在 sql 服务器查询 where 子句中使用 sqsh 变量,但无法使其工作。以下是我面临的问题的简单模拟。有人可以帮我解决这个问题

这按预期工作

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 被解释为您 table 中的列名,但是由于此列名不存在,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\';

希望对您有所帮助。