假设我有两个县:
每个人都拥有自己的网址:
我有一个存储过程,它接受3个变量来启用或禁用URL的服务。 @Enable
变量是必需的,但用户可以输入@County_Code
或@WebserviceURL
变量 - 或两者都有。但如果他们同时输入,我想验证记录是否存在于数据库中。
例如,
EXEC [dbo].usp_webservice_change_status
@enable = 1,
@county_code = 'A',
@webserviceURL = 'www.A.com';
应该执行并更新Enable标志。
但是如果我使用以下值执行,我希望返回一个错误,说明A区没有相应的www.B.com值。
EXEC [dbo].usp_webservice_change_status
@enable = 1,
@county_code = 'A',
@webserviceURL = 'www.B.com';
以下是完整的存储过程:
ALTER PROCEDURE [dbo].[usp_webservice_change_status]
@enable AS BIT,
@county_code AS CHAR(2) = NULL,
@webserviceURL AS VARCHAR(4000) = NULL
AS
BEGIN
SET NOCOUNT ON;
IF @enable IS NULL
RAISERROR ('The value for @enable should not be null', 15, 1);
IF ( @county_code IS NULL AND @webserviceURL IS NULL )
RAISERROR ('The value for @county_code and @webserviceURL cannot both be null', 15, 1);
IF ( @county_code IS NOT NULL AND @webserviceURL IS NULL )
UPDATE dbo.webservice_config
SET [enable] = @enable,
comments = CASE
WHEN @enable = 1 THEN 'Enabled by ' + SUSER_SNAME()
ELSE 'Disabled by ' + SUSER_SNAME()
END
WHERE county_code = @county_code
ELSE IF (@county_code IS NULL AND @webserviceURL IS NOT NULL )
UPDATE dbo.webservice_config
SET [enable] = @enable,
comments = CASE
WHEN @enable = 1 THEN 'Enabled by ' + SUSER_SNAME()
ELSE 'Disabled by ' + SUSER_SNAME()
END
WHERE webservice_URL = @webserviceURL
ELSE IF ( @county_code IS NOT NULL AND @webserviceURL IS NOT NULL )
UPDATE dbo.webservice_config
SET [enable] = @enable,
comments = CASE
WHEN @enable = 1 THEN 'Enabled by ' + SUSER_SNAME()
ELSE 'Disabled by ' + SUSER_SNAME()
END
WHERE ( county_code = @county_code AND webservice_URL = @webserviceURL )
END;
答案 0 :(得分:1)
如果我理解你想要的东西,你可以用另一个IF语句做到这一点......只需在PROCEDURE
END;
底部添加这两行代码
IF(@@ROWCOUNT) < 1
RAISERROR('Nothing Updated Due to Non Matching Records',15,1)
所以它看起来像这样
--all your other code
WHERE ( county_code = @county_code AND webservice_URL = @webserviceURL )
IF(@@ROWCOUNT) < 1
RAISERROR('Nothing Updated Due to Non Matching Records',15,1)
END;
如果你想要
,你也可以将整个事物包装在另一个IF
中
ELSE IF ( @county_code IS NOT NULL AND @webserviceURL IS NOT NULL )
IF(SELECT 1 FROM dbo.webservice_config WHERE county_code = @county_code AND webservice_URL = @webserviceURL) < 1
RAISERROR('Nothing Updated Due to Non Matching Records',15,1)
ELSE
UPDATE dbo.webservice_config
SET [enable] = @enable,
comments = CASE
WHEN @enable = 1 THEN 'Enabled by ' + SUSER_SNAME()
ELSE 'Disabled by ' + SUSER_SNAME()
END
WHERE ( county_code = @county_code AND webservice_URL = @webserviceURL )
END;
你也可以使用EXISTS
和其他语法而不是我使用的语法......只是一些例子。