简体   繁体   中英

MSSQL case with raiserror statement error?

I am trying to check if the availability group is running on correct primary replica.

I want to create a job that will fail if primary replica is not specific server.

SELECT CASE 
  WHEN primary_replica != @@SERVERNAME
  THEN  (RAISERROR('Wrong replica', 16, 1))
END 
FROM sys.dm_hadr_availability_group_states States

I expect the query to throw an error if primary replica is not the server that runs the job. However, I'm getting the error below:

Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'RAISERROR'.

Msg 102, Level 15, State 1, Line 3 Incorrect syntax near ')'.

You can't raise an error in a case expression like that. You can use EXISTS with IF instead. Note, this would run on servers where there wasn't an AG too... so if that isn't intended you'll want to account for that.

if exists (SELECT 1 from sys.dm_hadr_availability_group_states where  primary_replica != @@SERVERNAME)
BEGIN
  RAISERROR('Wrong replica', 16, 1)
END 

For newer versions, you can use sys.fn_hadr_is_primary_replica

If sys.fn_hadr_is_primary_replica ( db_name() ) <> 1   
BEGIN  
    RAISERROR('Wrong replica', 16, 1)
END  

You can try like this in SQL job step to check if Primary replica is not specific server:

DECLARE @ServerName NVARCHAR(256)  = @@SERVERNAME 
DECLARE @RoleDesc NVARCHAR(60)

SELECT @RoleDesc = a.role_desc
    FROM sys.dm_hadr_availability_replica_states AS a
    JOIN sys.availability_replicas AS b
        ON b.replica_id = a.replica_id
WHERE b.replica_server_name = @ServerName

IF @RoleDesc = 'PRIMARY'
BEGIN
    RAISERROR ('Error: Wrong replica',16,1 );
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM