【问题标题】:SQL - where column in another recordset from another databaseSQL - 来自另一个数据库的另一个记录集中的 where 列
【发布时间】:2018-05-06 03:35:01
【问题描述】:

我熟悉sql中的“IN”子句,例如

select * from table1 where myfield in (select myfield from table2)

我现在在两个数据库之间!我想从另一个数据库中选择电话在其他记录集中的记录集。我不直接使用 sql server。您可能会建议我使用服务器端语言的更复杂的方法,例如php或asp等

我在 classic asp 中的测试(connectionObject1 连接到第一个数据库,connectionObject2 连接到第二个数据库):

sql="select phone from persons"
recordset1.open sql,connectionObject1

sql="select * from persons where phone in ("& recordset1 &")"
recordset2.open sql,connectionObject2

Microsoft VBScript 运行时错误“800a000d”

类型不匹配

【问题讨论】:

  • 这两个数据库是在同一台服务器上吗?
  • 是的,它们在同一台服务器中,并且单个用户可以访问它们。但是我们为这两个连接对象指定了不同的“默认数据库”。
  • 您可能需要考虑使用cross database query,以便可以一起查询数据库。您需要根据查询的数据量和其他问题检查性能。但是您要查找的结果将是来自其中一个数据库的简单查询,而不是操纵 2 个单独的结果。

标签: php asp.net sql-server asp-classic where-in


【解决方案1】:

你的错误在这里:

sql="select * from persons where phone in ("& recordset1 &")"

您正在尝试连接字符串,但 recordset1 顾名思义是一个记录集,而不是字符串。

我刚刚查了一下。您应该能够使用GetString 将您的记录集转换为字符串:

sql = "select * from persons where phone in (" & 
        recordset1.GetString(adClipString, -1, ",", ",") &
      ")"

如果电话不是数字,则需要额外的引号:

sql = "select * from persons where phone in (" & 
        "'" &
        recordset1.GetString(adClipString, -1, "','", "','") &
        "'" &
      ")"

我可能对语法有误。在这种情况下,请查看您的文档。

【讨论】:

  • 这对我有用,但是我将 adClipString 更改为 2,而且我没有放置任何东西来代替 -1。我还必须从字符串末尾删除最后一个逗号和引号
【解决方案2】:

在 SQL 中使用完全限定的对象名称,这应该可以:

sql="select * from [DB1Name].[SchemaName].persons where phone in (select phone from [DB2Name].[SchemaName].persons)"

【讨论】:

  • 这很可爱。您甚至可以将其缩短为select * from persons。然而,OP 正在从位于两个不同数据库中的两个不同的 people 表中进行选择。
  • 你说得对,没注意……谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多