2013-04-03 139 views
0

我使用下面的代碼從我的表中獲取結果並將其綁定到gridview控件。 但我得到以下錯誤:sql查詢錯誤asp.net c#

"System.Data.SqlClient.SqlException: Incorrect syntax near 'x'" at "sqlda.Fill(ds1)"

我是ASP.NET新手,無法編寫好的查詢。

SqlConnection con = new SqlConnection(connStr); 
con.Open(); 
str = "WITH x AS (SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY PersonRFID ORDER BY DateStamp) FROM AISDb where action = 'IN'), y As(SELECT *, rna = ROW_NUMBER() OVER (PARTITION BY PersonRFID ORDER BY DateStamp)FROM AISDb where action='OUT') SELECT y.ID,x.ID,x.PersonName,y.PersonName,x.PersonRFID, DtATEDIFF(MINUTE, x.TimeStamp, y.TimeStamp) FROM x ,y where x.PersonRFID = y.PersonRFIDAnd x.rn=y.rnaAND cast(x.Datestamp as date) = cast(y.Datestamp as date)Order By x.PersonName"; 
com = new SqlCommand(str, con); 
sqlda = new SqlDataAdapter(com); 
ds1 = new DataSet(); 
sqlda.Fill(ds1); 
+0

顯然,在您的SQL語法錯誤...您是否嘗試過直接對數據庫運行查詢? – Brian 2013-04-03 19:06:32

+0

是的,它給出錯誤相同的錯誤,但我不明白什麼是錯誤 – saadsafdar 2013-04-03 19:12:16

回答

1

您的查詢中有幾個問題可能會導致您的錯誤。首先將DtATEDIFF更改爲DATEDIFF(這可能是一個錯字)。

更重要的是,修復你的間距。你有領域互相碰撞。

看到這個撥弄你的兩個例子,一個與間距:

http://sqlfiddle.com/#!3/47f7e/1

你得到,因爲這是錯誤:

y.PersonRFIDAnd x 

末的X是投擲錯誤。修復這個和之後的一個(之前),它應該工作。

+0

WITH x AS(SELECT *,rn = ROW_NUMBER()OVER(PARTITION BY PersonRFID ORDER BY DateStamp)FROM AISDb where action ='IN '),y As(SELECT *,rna = ROW_NUMBER()OVER(PARTITION BY PersonRFID ORDER BY DateStamp)FROM AISDb where action ='OUT')SELECT y.ID,x.ID,x.PersonName,y.PersonName,x .PersonRFID,DATEDIFF(MINUTE,x.TimeStamp,y.TimeStamp)FROM x,y其中x.PersonRFID = y.PersonRFID和x.rn = y.rna AND cast(x.Datestamp as date)= cast(y.Datestamp作爲日期)順序由x.PersonName;現在即時通訊使用此查詢,它會給與數據庫查詢時,但不是在c#中的罰款結果 – saadsafdar 2013-04-03 19:31:13

2

根據我的第一眼看,(沒有運行查詢),我可以看到一些錯誤。

datediff有錯字。

把空間在x.PersonRFID = y.PersonRFIDAnd x.rn=y.rnaAND

AND之前把order之前的空間date)Order By

+0

WITH x AS(SELECT *,rn = ROW_NUMBER()OVER(PARTITION BY PersonRF ORDER BY DateStamp)FROM AISDb where action ='IN' (SELECT *,rna = ROW_NUMBER()OVER(PARTITION BY PersonRFID ORDER BY DateStamp)FROM AISDb where action ='OUT')SELECT y.ID,x.ID,x.PersonName,y.PersonName,x.PersonRFID, DATEDIFF(MINUTE,x.TimeStamp,y.TimeStamp)FROM x,y其中x.PersonRFID = y.PersonRFID和x.rn = y.rna AND cast(x.Datestamp as date)= cast(y.Datestamp as date)按x.PersonName排序;現在即時通訊使用這個查詢,它會給與數據庫查詢時,但不是在c#中的罰款結果 – saadsafdar 2013-04-03 19:33:59

+0

調試代碼,把斷點,從本地或觀察窗口複製查詢,並將其粘貼到您的管理工作室,看看區別 – 2013-04-03 19:44:36

+0

你得到了什麼確切的錯誤?我需要更多描述才能回答問題? – 2013-04-04 12:51:30