Wednesday, March 21, 2012

Primary key on Linked server Issue

When I perform a simple query over a linked server that is looking for a
specific value using the primary key, SQL Server performs a constant scan in
stead of a remote query and returns 0 rows. Running the same query locally g
ives the expected result. When I force a data type conversion from integer t
o varchar in the criteria it gives the expected result.
Example problem query:
Select MyID
From Server2.MyDB.dbo.MyTable
Where MyID = 1
0 records are returned, but a record with a MyID = 1 does exist.
The following works as expected:
Select MyID
From Server2.MyDB.dbo.MyTable
Where MyID Like 1
Select MyID
From Server2.MyDB.dbo.MyTable
Where Cast(MyID As varchar) = 1
If i do a select on any other column, then the execution plan shows a remote
query and when I run it the expected rows are returned.
This is only happening on one server, and the only difference I can see is t
hat the database is set up for merge replication.
Any ideas as to why this is happening and how to permanently prevent it?
Thanks
Chris LongstaffAs a follow up to this message and to save anyone else the hassle of finding
the solution ... the issue is merge replication.
Basically the check constraints placed on the table for replication are used
when querying the linked server ... in my case i had a constraint of values
between 810 and 1200 ... when you query the linked server it checks for co
nstraints first and as I was querying for id =400 then it will never find it
as according to the check constraint that value cannot exist within the tab
le...
There are two possible solutions ... force a conversion to bypass the check
constraint ... or use OLEDB for ODBC as the driver as this will not attem
pt to use the check constraint.
Hope this helps anyone else who comes across this!sql

No comments:

Post a Comment