更新存储过程的返回值

时间:2015-04-13 17:33:44

标签: sql sql-server stored-procedures

我在SQL SERVER 2008上有这个存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SAVE1]
    @IDKEY float,
    @CPF nvarchar(20)
AS
BEGIN
    SET NOCOUNT ON;
BEGIN TRY
    UPDATE people SET NINUMBER = @CPF WHERE IDKEY = (SELECT IDKEY from contact where IDKEY= @IDKEY)
    SELECT 1 as retorno
END TRY
BEGIN CATCH
    SELECT 0 as retorno
END CATCH


END

但是如果我使用无效的IDKEY执行,则返回为“1”,但我认为会进入“CATCH”并返回“0”。我做错了什么?

2 个答案:

答案 0 :(得分:2)

在这种情况下,它不会抛出异常。您的子查询只会返回没有记录,因此您的更新语句将针对零记录执行。但它不会失败。

答案 1 :(得分:1)

您的查询没有失败,而是返回没有行,因此它返回1.尝试这样:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SAVE1]
    @IDKEY float,
    @CPF nvarchar(20)
AS

BEGIN
    SET NOCOUNT ON;

    UPDATE people SET NINUMBER = @CPF WHERE IDKEY = (SELECT IDKEY from contact where IDKEY= @IDKEY)
END

IF (@@ROWCOUNT > 0)
BEGIN
     SELECT 1 as retorno
END
ELSE 
BEGIN
    SELECT 0 as retorno
END