How to check if SQL Server exists before executing the code

I am using the following code to dynamically create a linked server

 select @tsql =	'use [master];
					EXEC master.dbo.sp_addlinkedserver @server = N'''+@pservername+''', @srvproduct=N''sql server'';
					EXEC master.dbo.sp_serveroption @server=N'''+ @pservername+''', @optname=N''data access'', @optvalue=N''true'';
					EXEC master.dbo.sp_serveroption @server=N'''+ @pservername+''', @optname=N''rpc'', @optvalue=N''true'';
					EXEC master.dbo.sp_serveroption @server=N'''+ @pservername+''', @optname=N''rpc out'', @optvalue=N''true'';
					EXEC master.dbo.sp_serveroption @server=N'''+ @pservername+''', @optname=N''use remote collation'', @optvalue=N''true'';
					EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N''' + @pservername+ ''', @locallogin = null , @useself = N''true'';'    

--print @tsql
IF @PrintFlag = 0 PRINT @tsql
ELSE   exec (@tsql)    

Open in new window

When a server does not exists I get the following error:

"OLE DB provider "SQLNCLI" for linked server "SERVER03" returned  message "Login timeout expired". "
LVL 35
Who is Participating?
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.

Aneesh RetnakaranDatabase AdministratorCommented:
you can use this

select * from master..sysservers where srvname = 'YourLinkedServerName'
YZlatAuthor Commented:
That's not what I meant. let's say I need to create a linked server from SERVER01 to SERVER03. SERVER03 was deleted. So executing sp_addlinkedserver would give an error.

How do I avoid that?
Aneesh RetnakaranDatabase AdministratorCommented:
from SQL server 2005 onwards you can call sp_testLinkedServer

otherwise just run a query against master database on your linked server, if it errors out, link is offline

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
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.