0

我想知道如果有 0 个结果,我必须怎么做才能在以下存储过程中引发异常,以便它可以选择 NULL 行?这是针对 MSSQL 的,非常感谢。

...

BEGIN TRY
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT
        NoteId,
        Url,
        Subject,
        Content,
        ExpiresAt,
        RemindAt
    FROM dbo.browsingnotes_Notes
    WHERE UserId = @UserId
        AND Hash = @Hash
END TRY
BEGIN CATCH
    SELECT
        NULL AS 'NoteId',
        NULL AS 'Url',
        NULL AS 'Subject',
        NULL AS 'Content',
        NULL AS 'ExpiresAt',
        NULL AS 'RemindAt'
END CATCH
4

3 回答 3

3

RAISERROR行得通吗?或者,正如@Candie 所说,THROW在 SQL 2012 中

您可以@@RowCount在第一次选择后检查,如果为 0,则选择第二次。

于 2012-09-08T16:20:54.237 回答
0

你可以阅读这篇文章

THROW [ { error_number | @local_variable },
        { message | @local_variable },
    { state | @local_variable }
] [ ; ]

链接:http: //msdn.microsoft.com/fr-fr/library/ee677615.aspx

于 2012-09-08T16:20:24.320 回答
0

UNION如果没有其他行,您可以简单地在结果集中添加一个 NULL 行:

SELECT
    NoteId, 
    Url, 
    Subject, 
    Content, 
    ExpiresAt, 
    RemindAt 
FROM dbo.browsingnotes_Notes 
WHERE UserId = @UserId 
    AND Hash = @Hash 
union
select NULL, NULL, NULL, NULL, NULL, NULL
  where not exists ( select 42 from dbo.browsingnotes_Notes where UserId = @UserId and Hash = @Hash )
于 2012-09-08T18:33:19.067 回答