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

时间:2017-10-19 09:50:59

标签: sql-server sqsh

我试图在sql server查询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'.

1 个答案:

答案 0 :(得分:0)

为了解释这里发生的事情,你应该看一下在变量扩展后发送到服务器的SQL缓冲区。为了做到这一点,你应该跳过&#39 ;;'快捷方式并提供' \ go -e'而在下一行(没有引号)。请注意,如果发生错误,这可能不会显示SQL缓冲区。

第一行将扩展为:

select * from information_schema.tables where table_name = PHONES

此处PHONES被解释为表中的列名,但由于此列名不存在,因此SQL Server会响应错误消息。

第二行将扩展为:

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

由于单引号,变量不会被sqsh扩展并按原样发送到服务器,因此是空结果集。

第三行将扩展为:

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

这看起来更像是字符串搜索参数,但由于QUOTED_IDENTIFIER选项可能默认处于启用状态,因此SQL Server仍在查找名为PHONES的列。

为了解决这个问题,您应该提供单引号,但仍希望sqsh扩展变量。您可以通过转义单引号来完成此操作,如:

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

希望这有帮助。

相关问题