MSSQL case with raiserror statement error?

时间:2019-01-09 22:08:16

标签: sql-server case alwayson raiserror

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

2 个答案:

答案 0 :(得分:1)

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  

答案 1 :(得分:0)

您可以在SQL作业步骤中尝试这样检查主副本是否不是特定的服务器:

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