2016-10-04 109 views
1

在我的工作上,我嘗試創建一個查詢以從SQL數據庫中獲取一些信息。這是行之有效的,但是當我嘗試使用日期範圍時,它會停止工作。如何從日期間的SQL數據庫中選擇東西?

我已想出了DATEPART函數,

SELECT 
* 
FROM 
InlogLog as il 
INNER JOIN 
ComputerIdentity as ci 
ON il.Computer = ci.Description 
WHERE ci.Location 
LIKE 'E18%' 
AND ci.MakeModelID = 9 
AND DATEPART(YY,il.Datum) = 2016 
AND DATEPART(MM,il.Datum) = 10 
AND DATEPART(DD,il.Datum) = 03 
ORDER BY il.Computer 

在上面的例子中,我不能指定兩個日期之間的範圍。 我還試圖使用本示例

SELECT 
* 
FROM 
InlogLog as il 
INNER JOIN 
ComputerIdentity as ci 
ON il.Computer = ci.Description 
WHERE ci.Location 
LIKE 'E18%' 
AND ci.MakeModelID = 9 
AND il.Datum = '2016-06-17 09:57:00.000' 

但是這導致一個錯誤消息

varchar數據類型爲datetime數據類型的轉換導致外的範圍內的值。

如何讓下一個示例工作?

SELECT 
* 
FROM 
InlogLog as il 
INNER JOIN 
ComputerIdentity as ci 
ON il.Computer = ci.Description 
WHERE ci.Location 
LIKE 'E18%' 
AND ci.MakeModelID = 9 
AND il.Datum '2016-06-17 09:57:00.000' BETWEEN '2016-06-18 00:00:00.000' 

回答

1

如果il.Datum爲varchar類型,那麼你應該對做一個鑄件它如下:

SELECT 
* 
FROM 
InlogLog as il 
INNER JOIN 
ComputerIdentity as ci 
ON il.Computer = ci.Description 
WHERE ci.Location 
LIKE 'E18%' 
AND ci.MakeModelID = 9 
AND CONVERT(DATE, ilDatum) >= CONVERT(DATE, '2016-10-01') 
AND CONVERT(DATE, ilDatum) <= CONVERT(DATE, '2016-10-04') 

注意:我已經將varchar轉換爲日期類型的列il.Dat嗯。如果沒有專門爲varchar類型進行轉換,則無法過濾日期。

+1

這是解決方案,非常感謝! –

2

問題是在語法(il.Datum '2016-06-17 09:57:00.000' BETWEEN '2016-06-18 00:00:00.000'),修改你的腳本如下圖所示。

如果您的列是varchar,請將其轉換爲datetime。

SELECT * 
FROM 
InlogLog as il 
INNER JOIN 
ComputerIdentity as ci 
ON il.Computer = ci.Description 
WHERE ci.Location 
LIKE 'E18%' 
AND ci.MakeModelID = 9 
AND CAST(il.Datum as datetime) BETWEEN '2016-06-17 09:57:00.000' AND '2016-06-18 00:00:00.000' 
1

貌似基準爲varchar數據類型,它應該是datetime數據類型的

試試這個

SELECT 
* 
FROM 
InlogLog as il 
INNER JOIN 
ComputerIdentity as ci 
ON il.Computer = ci.Description 
WHERE ci.Location 
LIKE 'E18%' 
AND ci.MakeModelID = 9 
AND il.Datum >='2016-06-17 09:57:00.000' il.Datum<= '2016-06-18 00:00:00.000' 
0
SELECT * FROM InlogLog as il INNER JOIN 
ComputerIdentity as ci 
ON il.Computer = i.Description WHERE ci.Location 
LIKE 'E18%' AND ci.MakeModelID = 9 AND 
DATEDIFF(DAY,ilDatum,'2016-06-17') <= 0 AND 
DATEDIFF(DAY,ilDatum,'2016-06-18') >=0 
相關問題