2011-06-16 62 views
12

在SQL 2008和C#4.0上使用存儲過程時,我無法檢索OUTPUT信息並從Select語句返回信息。我不斷收到「對象引用未設置爲對象的實例」。當我做ExecuteScalar()我得到的行,但不是數據。在那裏發現了幾個例子,他們看起來像我在做什麼,所以我想我在我面前丟失了一些簡單的東西。謝謝。SQL OUTPUT存儲過程不能與ExecuteReader配合使用

存儲過程

USE [PhoneDb] 
GO 
/****** Object: StoredProcedure [dbo].[TestPagingProcedure] Script Date: 06/16/2011 08:39:03 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

ALTER PROCEDURE [dbo].[TestPagingProcedure] 
    -- Add the parameters for the stored procedure here 
    @startRowIndex int, 
    @maximumRows int, 
    @totalRows int OUTPUT 


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

DECLARE @first_id UNIQUEIDENTIFIER 
DECLARE @startRow int 

SET @startRowIndex = (@startRowIndex - 1) * @maximumRows 

IF @startRowIndex = 0 
SET @startRowIndex = 1 

SET ROWCOUNT @startRowIndex 

SELECT @first_id = ExtensionGUID FROM ExtItem ORDER BY ExtensionGUID 

PRINT @first_id 

SET ROWCOUNT @maximumRows 

SELECT 
ExtensionGUID, AesExt, AesHashPassword, ToNumber, AgentExt, Name, JpgImageName, BigImageName, WbmpImageName 
FROM ExtItem WHERE 
ExtensionGUID >= @first_id 
ORDER BY ExtensionGUID 

SET ROWCOUNT 0 

-- GEt the total rows 

SELECT @totalRows = COUNT(ExtensionGUID) FROM ExtItem 

END 

C#代碼

public bool GetPagedResults(string startRowIndex, string maxRows, ref double totalRowsReturned) 
    { 
     bool IsSuccess = false; 
     string clearPassword = ""; 
     Log.WriteLine("GetExtList : ENTERED GETEXTITEM: ", Log.DEBUG_LEVEL.VERBOSE); 
     SqlConnection MyConnection = null; 
     EnDecrypt hasher = null; 

     try 
     { 
      if (SQLLookup.DatabaseString == "") 
      { 
       Log.WriteLine("GetPagedResults : SQLLookup.DatabaseString is empty:", Log.DEBUG_LEVEL.VERBOSE); 
       SQLLookup.SQLFinder(); 
       Log.WriteLine("GetPagedResults : SQL FINDER RUN: SQLLookup.DatabaseString:'" + SQLLookup.DatabaseString + "'", Log.DEBUG_LEVEL.VERBOSE); 
      } 

      Log.WriteLine("GetPagedResults: SQL Server '" + SQLLookup.DatabaseString + "'", Log.DEBUG_LEVEL.VERBOSE); 

      _extItemList.Clear(); // Keep new records from just being appended to existing list. 

      hasher = new EnDecrypt("SetMyKey", "SaltGenerator"); 

      // Create a Connection to SQL Server 
      MyConnection = new SqlConnection(@"Data Source= " + SQLLookup.DatabaseString + @"; Initial Catalog=PhoneDb;Integrated Security=True"); 

      SqlCommand myCommand = new SqlCommand("TestPagingProcedure", MyConnection); 
      myCommand.CommandType = CommandType.StoredProcedure; 

      /* ASSIGN PARAMETERS */ 
      myCommand.Parameters.Add(new SqlParameter("@startRowIndex", startRowIndex)); 
      myCommand.Parameters.Add(new SqlParameter("@maximumRows", maxRows)); 
      myCommand.Parameters.Add("@totalRows", SqlDbType.Int, 4); 
      myCommand.Parameters["@totalRows"].Direction = ParameterDirection.Output; 


      Log.WriteLine("GetPagedResults:3 After try ", Log.DEBUG_LEVEL.VERBOSE); 
      Log.WriteLine("GetPagedResults:3 startRowIndex = " + startRowIndex + " maxRows = " + maxRows, Log.DEBUG_LEVEL.VERBOSE); 
      MyConnection.Open(); 
      SqlDataReader Reader = myCommand.ExecuteReader(); 

      Log.WriteLine("GetPagedResults BEFORE WHILE LOOP", Log.DEBUG_LEVEL.VERBOSE); 
      while (Reader.Read()) 
      { 
       /* BUILD EXT ITEM*/ 
       ExtItem extItem = new ExtItem(); 
       if (Reader.IsDBNull(0) || Reader.GetGuid(0) == Guid.Empty) 
        extItem.ExtensionGUID = Guid.Empty; 
       else 
        extItem.ExtensionGUID = Reader.GetGuid(0); 

       if (Reader.IsDBNull(1) || Reader.GetString(1) == "") 
        extItem.AesExt = "No value"; 
       else 
        extItem.AesExt = Reader.GetString(1); 


       /* ADD ITEM TO LIST */ 
       AddItem(extItem); 

       //Log.WriteLine("GetExtList extItem: " + extItem.ToString(), Log.DEBUG_LEVEL.VERBOSE); 
      } 

      // get the total rows 
      Log.WriteLine("GetPagedResults: New Total number of pages: " + (int)myCommand.Parameters[2].Value, Log.DEBUG_LEVEL.TERSE); 
      // totalRowsReturned = myCommand.Parameters["@totalRows"]; 

      IsSuccess = true; 

      MyConnection.Close(); 
      Log.WriteLine("GetPagedResults: RETURNING:", Log.DEBUG_LEVEL.VERBOSE); 
     } 

     catch (Exception ex) 
     { 
      Log.WriteLine("GetPagedResults: Unable to retrieve Extension list. Caught Exception " + ex.Message, 
       Log.DEBUG_LEVEL.TERSE); 
      IsSuccess = false; 
     } 

     MyConnection.Close(); 

     return IsSuccess; 
    } 
+0

使用'SELECT TOP(@maximumRows)...'而不是'SET ROWCOUNT'好得多。通過這種方式,查詢優化器*知道*您只需要最上面的行,並且可以爲此生成一個優化的計劃。 – 2011-06-16 18:26:35

回答

31

據,http://msdn.microsoft.com/en-us/library/ms971497,則必須在處理輸出參數之前關閉DataReader。

+0

謝謝Johan,那是我需要做的。我把它放在我的循環之後,而不是在關閉之後。謝謝你,先生!!我會記住Remus – gcoleman0828 2011-06-27 01:15:40

+0

非常感謝,我知道答案在這裏。我有同樣的問題。 – Johan 2011-06-30 08:35:41