Issue With returned data linked between local database and a Linked Server Database

Anthony C 1 Reputation point
2022-02-09T16:38:19.847+00:00

Hello Forum

We have a bit of a weird issue. Essentially we are attempting to link data; one set is compiled as a Table Variable and the other is data on a linked Server.

On both Servers, we are linking the data with a simple inner join. Both columns are the same data type (int); both databases are using the same collation, both Servers are using the same collation.

The query is expected to return five rows BUT

SELECT ash.ApplicationStatusHistoryId,
ash.ApplicationID,
ash.IsCurrent,
ash.PrimaryStatusId,
ash.ApplicationStatusId,
ash.SetDate
FROM [SERVER].[DATABASE].[dbo].[ApplicationStatusHistory] ash
INNER JOIN @Karim152 a
ON
ash.ApplicationID = a.ApplicationID

Returns one row where as

SELECT ash.ApplicationStatusHistoryId,
ash.ApplicationID,
ash.IsCurrent,
ash.PrimaryStatusId,
ash.ApplicationStatusId,
ash.SetDate
FROM [SERVER].[DATABASE].[dbo].[ApplicationStatusHistory] ash
INNER JOIN @Karim152 a
ON
CAST(ash.ApplicationID AS INT) = a.ApplicationID--INT
returns the expected five rows.

When we pull the data across into a new table and run
SELECT ash.ApplicationStatusHistoryId,
ash.ApplicationID,
ash.IsCurrent,
ash.PrimaryStatusId,
ash.ApplicationStatusId,
ash.SetDate
FROM DBAScratchPad.[dbo].[ApplicationStatusHistory] ash

INNER JOIN @Karim152 a
ON
ash.ApplicationID = a.ApplicationID

This also returns five rows.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,892 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Anthony C 1 Reputation point
    2022-02-14T11:24:30.047+00:00

    Both Servers are SQL Server with the same collation.

    Main Server is 2017 Enterprise
    Linked Server IS 2012 Enterprise SP4


  2. Tom Phillips 17,716 Reputation points
    2022-02-14T16:36:22.107+00:00

    My guess is ash.ApplicationID is a varchar with leading spaces. ie " 1" <> "1". Casting it to INT is doing a proper compare.