SQL 加入 OPENQUERY 协助

SQL JOIN OPENQUERY Assistance

寻求有关处理以下问题的最佳方法的建议

TBL1(本地 SQL 数据库)其中 ID = varchar

TBL2(远程 MYSQL 数据库)其中 ID = INT

WITH TBL1 as (
SELECT 
     [Results]  as 'ID'
 FROM [DB].[results]
),

TBL2 as (


select * from openquery(LINKEDSERVER,'select  ID, Name from DB')

) 

Select  
   TBL1.[ID],

   TBL2.[NAME] 
FROM [DB]
left outer JOIN TBL1 ON TBL1.ID = TBL2.ID

尝试了几种不同的方法,例如 CAST/CONVERT,但最终出现“转换 varchar 值时转换失败 '12345”之类的错误 ' 到数据类型 int。" 或为 TBL2 获取所有 NULLS。

尝试了以下操作:

WITH TBL1 as 
( 
SELECT CAST(ISNULL([Results],'0') AS INT) as 'ID' 
FROM [DB].[results] 
), 
TBL2 as ( select * from openquery(LINKEDSERVER,'select ID, Name from DB') 
) 

Select TBL1.[ID], TBL2.[NAME] 
FROM TBL1 Left Outer join TB2 ON TBL1.ID = TBL2.ID

这导致“转换 varchar 值时转换失败 '12345 ' 数据类型为 int。"

也尝试过:

WITH TBL1 as ( SELECT [Results] as 'ID' FROM [DB].[results] 
), 

TBL2 as ( select * from openquery(LINKEDSERVER,'select CONVERT(ID, CHAR) AS ID, Name from DB') 
) 

Select TBL1.[ID], TBL2.[NAME] 
FROM TBL1 Left Outer join TB2 ON TBL1.ID = TBL2.ID 

这会导致显示 TBL1.ID 值,但所有 TBL2.Name 值都是 NULL

选项 1:尝试在房子的 MySQL 一侧将 INT 转换为 varchar。尝试在传递给 LinkedServer 的 sql 语句中正确执行此操作。

WITH TBL1 as ( SELECT [Results] as 'ID' FROM [DB].[results] 
), 

TBL2 as ( select * from openquery(LINKEDSERVER,'select CONVERT(ID, CHAR) AS ID, Name from DB') 
) 

Select TBL1.[ID], TBL2.[NAME] 
FROM TBL1 Left Outer join TB2 ON TBL1.ID = TBL2.ID 

另一个选择当然是相反的(如果你想通过INT加入)

WITH TBL1 as 
( 
SELECT CAST(ISNULL(TRIM([Results]),'0') AS INT) as 'ID' 
FROM [DB].[results] 
), 
TBL2 as ( select * from openquery(LINKEDSERVER,'select ID, Name from DB') 
) 

Select TBL1.[ID], TBL2.[NAME] 
FROM TBL1 Left Outer join TB2 ON TBL1.ID = TBL2.ID 

你的语法看起来不对。 DB C 来自哪里? DB 不是架构名称吗?

WITH TBL1 as (
SELECT 
     [Results]  as ID
 FROM [DB].[results]
),
TBL2 as (
    select * from openquery(LINKEDSERVER,'select  ID, Name from DB')
) 

Select  
   TBL1.[ID],
   TBL2.[NAME] 
FROM TBL2 left outer JOIN TBL1 ON try_cast(TBL1.ID as int) = TBL2.ID;

感谢大家的帮助。这就是它起作用的原因:

WITH TBL1 AS (
    SELECT REPLACE(REPLACE(ID, CHAR(13), ''), CHAR(10), '') 
    FROM DB
    WHERE ISNUMERIC(REPLACE(REPLACE(ID, CHAR(13), ''), CHAR(10), '')) = 1

),
TBL2 AS (
    SELECT *
    FROM OpenQuery(
        LINKEDSERVER,
        'SELECT id, name FROM DB'
    )
)
SELECT 
    TBL1.ID
    ,TB2.Name
FROM TBL2
LEFT OUTER JOIN TBL1 ON TBL1.ID = TBL2.id