Checking for existance of a remote row

-- -- 922 Reputation points
2021-07-14T02:20:08.257+00:00

Hi

I need to check if a row for SELECT 1 FROM Staff WHERE ID = @ID exists on a remote SQL Server. I am trying below code;

Declare @ID int = 10  
Declare @STAFFID int = -1  
Declare @sql nvarchar(max)  
  
Set @sql='SELECT @STAFFID = ID   
          FROM OPENROWSET(''SQLNCLI'',''...''; ''...''; ''...'',''SELECT * FROM Staff where ID = ' + convert(varchar(10), @ID) + ''')'  
  
Exec(@sql)  
  
IF @STAFFID = -1  
  PRINT 'Not Found'  
ELSE  
  PRINT 'Found!!!'  

However I am getting a 'Must declare the scalar variable "@STAFFID"' error. How can I check if the remote row exits?

Thanks

Regards

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,624 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. -- -- 922 Reputation points
    2021-07-14T03:56:56.84+00:00

    Hi

    This works for me.

    IF EXISTS (SELECT 1
    FROM OPENDATASOURCE('SQLNCLI11', 'SERVER=...;DATABASE=MyDB;UID=...;PWD=...;').MyDB.dbo.Staff
    WHERE ID = @ID)
      PRINT 'Found!'
    ELSE
      PRINT 'Not Found!'
    

    Regards


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.