2014-04-10 33 views
0

我想在Startpoint和EndPoint之間獲取ID,但無法過濾query.When編寫命令時沒有那麼大,那麼運算符就可以工作,但會搜索所有表。爲什麼SQL邏輯運算符在c#命令中不起作用?

我找不出如何解決這個問題。這是我的代碼;請你能幫助我嗎?

public async Task<int> TaskSearchSqlTweetIDText(string TweetText, string Query, int StartPoint, int EndPoint) 
    { 
     SqlConnection conn = new SqlConnection(Tools.ConnectionString); 
     SqlCommand comm = new SqlCommand("select ID from Tweets where @VsTweetText=TweetText and ID<@VsEndPoint and ID>@VsStartPoint", conn); 

     comm.Parameters.AddWithValue("@VsTweetText", TweetText); 

     comm.Parameters.Add("@VsStartPoint", SqlDbType.Int); 
     comm.Parameters["@VsStartPoint"].Value = StartPoint; 

     comm.Parameters.Add("@VsEndPoint", SqlDbType.Int); 
     comm.Parameters["@VsEndPoint"].Value = EndPoint; 


     if (conn.State == ConnectionState.Closed) conn.Open(); 

     object sonuc = await comm.ExecuteScalarAsync(); 
     conn.Close(); 

     if (sonuc != null) 
     { 
      return (int)sonuc; 

     } 
     else 
     { 
      return 0; 

     } 
    } 
+0

當您在SSMS中嘗試相同的查詢時,您會得到什麼 - 有多少條目? '從推文中選擇ID @VsTweetText = TweetText和ID <@VsEndPoint和ID> @ VsStartPoint' – Nayan

+0

請注意(這也在我的答案中):您的查詢也爲'TweetText'過濾,所以您的要求*我想在Startpoint和EndPoint *之間獲取ID不完整。它應該讀取*我想在TweetText與給定值*匹配的Startpoint和EndPoint之間獲取ID。 –

回答

0

你沒有在你的問題中說明這一點,所以我假設你沒有從查詢中得到任何結果,因爲它是?

也許根本沒有ID的嚴格更大,嚴格小於您提供的範圍TweetText匹配的推文。您可以調試以查看StartPointEndPoint的值,以及數據庫中是否確實存在與TweetText匹配的嚴格位於它們之間的ID。

您可以更改語句如下,以包含StartPointEndPoint的值。

select ID from Tweets 
where @VsTweetText = TweetText 
    and ID <= @VsEndPoint 
    and ID >= @VsStartPoint 

甚至

select ID from Tweets 
where @VsTweetText = TweetText 
    and ID BETWEEN @VsStartPoint AND @VsEndPoint 

也請注意,上面的語句很可能返回多個記錄,但你在代碼中使用ExecuteScalar,讓你在使用的第一個ID你遇到 - 隨機。如果你真的只對一個 ID感興趣,你應該修改你的查詢,以便更容易預測哪一個被選擇。

也許是這樣的:

select top 1 ID from Tweets 
where @VsTweetText = TweetText 
    and ID BETWEEN @VsStartPoint AND @VsEndPoint 
order by ID desc 

這將返回範圍內發現的最大ID。

+0

感謝您的關注@Thorsten Dittmar'Select Top 1'解決了這個問題。 – Euphoria

+0

@Euphoria奇怪 - 它確實不應該有所作爲,因爲'ExecuteScalar'被定義爲返回* first *記錄的* first *列的值(不管那條記錄是什麼)。 'TOP'條款(和'ORDER BY'一起)確保結果是可預測的。 **請注意:如果沒有'ORDER BY',應該沒有'TOP'!** –

0

如果您在SSMS中的查詢中獲得了多個條目,您可能需要查看條件 - 爲什麼它返回多個條目。收緊where條款,使其精確。

where @VsTweetText = TweetText 
    and ID < @VsEndPoint 
    and ID > @VsStartPoint 

但是,如果你想只得到第一個條目(如果你這樣做),然後使用此:

select top 1 ID from Tweets 
where @VsTweetText = TweetText 
    and ID < @VsEndPoint 
    and ID > @VsStartPoint 

,因爲你正在使用ExecuteScalarAsync這隻能返回一個標對象。

+0

非常感謝你@Nayan'Top 1'解決了問題。 – Euphoria