0

我正在使用一个 C# 程序,该程序调用在 SQL Server 2008 R2 实例上执行的 SQL 语句。这是 SQL 调用:

SELECT TOP 1 as1.AssetTagID, as1.TagID, as1.CategoryID, as1.Description,
    as1.HomeLocationID, as1.ParentAssetTagID 
    FROM Assets AS as1 ORDER BY ar.DateScanned DESC
INNER JOIN AssetsReads AS ar
ON as1.AssetTagID = ar.AssetTagID
WHERE (ar.ReadPointLocationID='Readpoint1' OR ar.ReadPointLocationID='Readpoint2')
    AND as1.TagID!='000000000000000000000000';

我得到一个SQLException周围的内部。异常文本如下:

System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'INNER'.

我也可以将堆栈跟踪放在此处,但我觉得这会使问题变得混乱。这是我在调用中使用的 C# 代码中的实际字符串:

"SELECT TOP 2 as1.AssetTagID, as1.TagID, " +
    "as1.CategoryID, as1.Description, as1.HomeLocationID," +
    "as1.ParentAssetTagID FROM Assets AS as1 ORDER BY ar.DateScanned DESC\n" +
    "INNER JOIN AssetsReads AS ar ON as1.AssetTagID = ar.AssetTagID\n" +
    "WHERE (ar.ReadPointLocationID='" + IntegrationService.Lane2Zones[0] + 
    "' OR ar.ReadPointLocationID='" + IntegrationService.Lane2Zones[1] + "')\n" +
    "AND as1.TagID!='000000000000000000000000';"
4

2 回答 2

4

您的 ORDER BY 语句不能在那里。把它移到最后

我还将发表强制性的“不要这样做”演讲。像这样连接 SQL 字符串会使您面临 SQL 注入攻击。SO 和 Google 上有很多关于这方面的信息,所以我不会深入讨论,但您绝对应该考虑将其设为参数化查询。

于 2013-08-13T18:26:50.897 回答
0

Like he said... your order by clause was out of order :)

SELECT TOP 1 as1.AssetTagID,
         as1.TagID,
         as1.CategoryID,
         as1.Description,
         as1.HomeLocationID,
         as1.ParentAssetTagID
FROM   Assets AS as1
   INNER JOIN AssetsReads AS ar
           ON as1.AssetTagID = ar.AssetTagID
WHERE  ( ar.ReadPointLocationID = 'Readpoint1'
      OR ar.ReadPointLocationID = 'Readpoint2' )
   AND as1.TagID != '000000000000000000000000'
ORDER  BY ar.DateScanned DESC; 

I'll also note that using schema qualified objects is recommended by Microsoft (http://technet.microsoft.com/en-us/library/ms190387(v=sql.105).aspx). Also you should use parenthesis around your top (value) statement.

SELECT TOP (1) [as1].[AssetTagID],
           [as1].[TagID],
           [as1].[CategoryID],
           [as1].[Description],
           [as1].[HomeLocationID],
           [as1].[ParentAssetTagID]
FROM   [<schema>].[Assets] AS [as1]
   INNER JOIN [<schema>].[AssetsReads] AS [ar]
           ON [as1].AssetTagID = [ar].[AssetTagID]
WHERE  ( [ar].[ReadPointLocationID] = 'Readpoint1'
      OR [ar].[ReadPointLocationID] = 'Readpoint2' )
   AND cast([as1].TagID AS [INT]) != 0
ORDER  BY [ar].[DateScanned] DESC; 
于 2013-08-13T19:03:15.183 回答