Incorrect syntax near ')'.


I try to compare the jobs between two servers :

DECLARE @server varchar(30);
DECLARE @Text nvarchar(max);
set @server = 'TESTSRV'

SET @Text= N'IF EXISTS (select * from sysjobs where name not in (select name from ['+ @server + '].msdb.dbo.sysjobs))'
EXEC (@Text)

RAISERROR('count, level 11', 11, 1)


Msg 102, Level 15, State 1, Line 1

Msg 50000, Level 11, State 1, Line 11
count_jobs, level 11

How can I resolve it?

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Russell FoxDatabase DeveloperCommented:
Don't bother with dynamic SQL:
FROM msdb.dbo.sysjobs j1
	LEFT JOIN STATESERVER1.msdb.dbo.sysjobs j2
		ON =

Open in new window

Jose TorresCertified Database AdministratorCommented:
The IF EXISTS needs more, it is an if statement so its waiting on something to do after it runs the query inside.

That being said try the following it's cleaner.
As an admin it is sometimes a necessary evil to use dynamic sql when interrogating various sql servers.

DECLARE @server varchar(30)
DECLARE @Text nvarchar(max)
DECLARE @JobsServerB TABLE (name NVARCHAR(128))
SET @server = 'TESTSRV'
SET @Text = 'SELECT name FROM ' + QUOTENAME(@server) + '.msdb.dbo.sysjobs'
INSERT INTO @JobsServerB EXEC (@Text)

SELECT name FROM @JobsServerB
SELECT name FROM msdb.dbo.sysjobs 

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
bibi92Author Commented:
Thanks a lot regards
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.