我试图在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'.发布于 2017-10-22 14:32:23
要解释这里发生了什么,您应该查看变量扩展后发送到服务器的SQL缓冲区。为了做到这一点,您应该跳过';‘快捷方式,并在下一行中提供'\go -e’代替(没有引号)。请注意,在发生错误时,这可能不会显示SQL缓冲区。
第一行将扩大到:
select * from information_schema.tables where table_name = 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\\';希望这能有所帮助。
https://stackoverflow.com/questions/46827172
复制相似问题