SET NOCOUNT ON brings back messages in SQL Server Management Studio

我的未来我决定 提交于 2019-12-21 23:30:36

问题


I have the following stored procedure:

ALTER PROCEDURE [dbo].[spTitle_GetTitleById]
(
   @TitleId INT
)

AS

BEGIN

   SET NOCOUNT ON;

   SELECT
      Id,
      Name,
      Active
   FROM
      Title
   WHERE
      Id = @TitleId

END

I was told to use SET NOCOUNT ON; if I don't want messages to be returned. I ran this stored procedure through SQL Server Management Studio 2008 and I got the following message:

(1 row(s) affected)

This is still a message. One of our DBAs said that this will be the case, but when it is run through an application it will not return any messages. Is there a way that I can test to see if messages were returned or not when I use SET NOCOUNT ON; I don't want to assume, I want to know.

I right clicked the stored procedure and selected Execute Stored Procedure... I then set it to OFF, and I got:

(1 row(s) affected)
(1 row(s) affected)

So setting it to ON or OFF it still brought back messages in the Messages tab in the results panel.

Just another question, when will it be wise (in what scenarios) to use SET NOCOUNT OFF;?


回答1:


SET NOCOUNT ON is reset when the procedure exits and it goes up the call stack. When you execute the procedure from SSMS it generates a script like the following.

DECLARE @return_value int

EXEC    @return_value = [dbo].[spTitle_GetTitleById]
        @TitleId = 1

SELECT  'Return Value' = @return_value  /*Message comes from here*/

If youi wanted to avoid that for some reason you would need to SET NOCOUNT ON in the outer batch. See SET NOCOUNT ON usage for some discussion about the merits of having this ON or OFF




回答2:


Just another question, when will it be wise (in what scenarios) to use SET NOCOUNT OFF?

See What are the advantages and disadvantages of turning NOCOUNT off in SQL Server queries? For the benefits turning SET NOCOUNT ON

As for why you would want to turn this off (so that rowcounts are returned) - you need this off whenever you want to be able to tell how many rows were affected in situations where there is no resultset, or you wish to be able to get a rowcount without first reading through the entire resultset.

For example in .Net the DataAdapter class uses rowcounts and so setting NOCOUNT ON causes issues when editing or deleting data (source).




回答3:


That is not correct, script out the proc an make sure it is not OFF instead o ON, if it is ON it should not return (1 row(s) affected) messages

Also how are you executing the proc

is is just this

exec spTitle_GetTitleById 1


来源:https://stackoverflow.com/questions/5884222/set-nocount-on-brings-back-messages-in-sql-server-management-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!