SQL 2012中的LEFT或SUBSTRING函数错误

8 浏览
0 Comments

SQL 2012中的LEFT或SUBSTRING函数错误

我正在尝试执行以下的SQL查询:

SELECT TMP.*,COUNT(*) OVER () AS rCount 
FROM (
    SELECT venueID, 
           venueName AS venueName, 
           venueSpanish AS spanish, 
           venueAddress + ', ' + venueCity + ', ' + venueState + ' ' + venueZip AS venueAddress, 
           venueLatLong AS coordinates, 
           CONVERT(VARCHAR, venueEventDate, 101) + ' @ ' + CONVERT(VARCHAR,venueTime) AS dateAndTime, 
           SUBSTRING(venueLatLong, 1, CHARINDEX(',', venueLatLong)-1) AS Lat, 
           SUBSTRING(venueLatLong, CHARINDEX(',', venueLatLong) + 1, 1000) AS Lng, 
           (round(3959 * acos (cos(radians('35.0935409')) * 
                cos(radians(SUBSTRING(venueLatLong, 1, CHARINDEX(',', venueLatLong)-1))) * 
                cos(radians(SUBSTRING(venueLatLong, CHARINDEX(',', venueLatLong) + 1, 1000)) - 
                radians('-85.0856761')) + 
                sin(radians('35.0935409')) * 
                sin(radians(SUBSTRING(venueLatLong, 1, CHARINDEX(',', venueLatLong)-1)))), 1, 1)) AS distance 
    FROM meetUpMarkers) TMP 
WHERE distance < 30 

然而,当我执行时,出现以下错误:

Msg 537, Level 16, State 2, Line 1

Invalid length parameter passed to the LEFT or SUBSTRING function.

希望能得到帮助解决这个问题!

0
0 Comments

问题出现的原因是在代码中使用了LEFT和SUBSTRING函数,而在venueLatLong变量中没有逗号,导致长度为-1。解决方法是将经度和纬度分别存储在两个数值类型的列中,而不是使用VarChar类型。由于某些记录没有正确的经纬度格式("xx.xxxxxx,-xx.xxxxxxx"),所以会出现错误。

0
0 Comments

问题可能是由于传递给substring函数的参数出现错误。查询中重复出现了这个条件。

CHARINDEX(',', venueLatLong)

如果venueLatLong中不包含,,那么传递给substring的参数是无效的。

可以通过包含一个where子句来避免这个问题。

WHERE CHARINDEX(',', venueLatLong) > 0

是的,看起来一些记录的纬度/经度没有使用"xx.xxxxxx,-xx.xxxxxxx"的格式,因此导致了这个错误。

0