2012-11-05 46 views
1

在閱讀本網站時,我想以下代碼會返回添加到我的數據庫的項目的ID,但是我想填充的int值並未顯示在範圍內。下面是我的插入語句的代碼:SCOPE_INDENTITY()不工作是否返回null?

foreach (ExOb exc in exobject) 
      { 

       Type type = exc.GetType(); 
       //Add a weight exercise 
       if (type == typeof(Weights)) 
       { 

        Weights thisweight = (Weights)exc; 
        string InsertWeight = ("INSERT INTO WeightExercise (ExcerciseName, Duration, Sets, DiaryId) VALUES (@name, @time, @sets, @DiaryId) SET @ID = SCOPE_IDENTITY();"); 

         com = new SqlCommand(InsertWeight, con); 
         com.Parameters.AddWithValue("@name", thisweight.ExcerciseName); 
         com.Parameters.AddWithValue("@time", thisweight.WeightDuration); 
         com.Parameters.AddWithValue("@sets", thisweight.TotalSets); 
         com.Parameters.AddWithValue("@DiaryId", results[0]); 
         com.Parameters.Add("@ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output; 
         con.Open(); 
         com.ExecuteNonQuery(); 
         int ID = (int)com.Parameters["@ID"].Value; 

         con.Close(); 


       } 
       else if (type == typeof(Cardio)) 
       { 
        Cardio thiscardio = (Cardio)exc; 


       } 

      } 
     } 

數據庫用Weight Weight詳細信息更新。我在調試時檢查過,命令參數@ID保存最新條目的ID。 Int ID在調試時不會顯示在當地人身上,如果我觀看它,我會得到:

ID The name 'ID' does not exist in the current context 

我在做什麼錯在這裏?

+1

這是一個範圍界定問題嗎? ID只存在於if(type == typeof(Weights))塊 – akatakritos

+0

我已經用select scope_identity()做了這個,但是我看不出你的代碼有什麼問題。 – Paparazzi

+0

這裏有一個'IDENTITY'專欄嗎? –

回答

2

調試時,我已經確認並命令參數@ID擁有最新的條目的 ID。

這表明您當前使用的數據庫代碼運行良好。調試時

詮釋ID不當地人出現了,如果我看着它我 得到...

這是你的問題的根源。問題在於您已將範圍ID設置爲

if (type == typeof(Weights)) 

塊。在該塊之外,標識符ID沒有意義。

聲明ID在此過程的範圍的頂部,您應該能夠在本地中看到它或添加監視。

+0

這就是它雖然所有其他答案都非常有幫助 - 移動聲明並沒有在當地人看到或觀看,但完成我的代碼並用它來更新另一個表中的列。謝謝,並表示歉意,有點毫無意義的問題! – Luthervd

0

我假設表有一個標識列。

試着這樣做:

string InsertWeight = ("INSERT INTO WeightExercise 
(ExcerciseName, Duration, Sets, DiaryId) VALUES (@name, @time, @sets, @DiaryId); SELECT SCOPE_IDENTITY()"); 

然後,而不是com.ExecuteNonQuery()使用int ID = (int) com.ExecuteScalar();

對於您的實際問題,請嘗試在插入語句之後和SET之前放入分號。原因是因爲你在同一個陳述中。當SCOPE_IDENTITY()被調用時,還沒有插入。您需要終止聲明(;),然後調用SCOPE_IDENTITY();

4

SCOPE_IDENTITY返回插入到同一範圍內的標識列的最後一個標識值。您需要使用ExecuteScalar而不是ExecuteNonQuery找回它:

因此改變你的SQL先:

「INSERT INTO WeightExercise(ExcerciseName,持續時間,集合,DiaryId) VALUES(@name,@time ,@sets,@DiaryId); SELECT SCOPE_IDENTITY();「

,那麼你可以通過這種方式獲取ID:

ID = (int)com.ExecuteScalar(); 
+0

OP正在更新一個指定爲輸出的參數 - 它應該與原來一樣好,與執行查詢 –

相關問題