Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored procedure to get the status of a linked server

I'm trying to create a stored procedure to get the status of a linked server to prevent errors when trying to execute anything on it. I saw some examples online, but I'm not having any success with those.

Here is my code:

ALTER PROCEDURE [dbo].[checkLinkedServer] 
    @servername ntext
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @retval int = 0;
    BEGIN TRY
        EXEC @retval = sys.sp_testlinkedserver @servername;
        SELECT 1;
    END TRY
    BEGIN CATCH
        SELECT 0;
    END CATCH;      
END

I'm always getting a return value of 0 - no matter if the linked server exists or not.

Any ideas what I'm doing wrong here?

like image 487
Rafael Avatar asked Dec 07 '25 04:12

Rafael


1 Answers

Your @servername parameter needs to be of the type sysname not ntext as the error message says

If you can't change the parameter going into the procedure then consider creating a new variable inside the proc and doing a convert:

ALTER PROCEDURE [dbo].[checkLinkedServer] 
    @servername ntext
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @retval int = 0,
            @sysservername sysname;
    BEGIN TRY
        SELECT  @sysservername = CONVERT(sysname, @servername);
        EXEC @retval = sys.sp_testlinkedserver @sysservername;
        SELECT 1;
    END TRY
    BEGIN CATCH
        SELECT 0;
    END CATCH;      
END
like image 158
collusionbdbh Avatar answered Dec 08 '25 17:12

collusionbdbh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!