Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,624 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
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