内部联接的SQLException

时间:2013-08-13 18:25:04

标签: c# sql sql-server-2008-r2 inner-join

我正在使用一个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';

我在INNER周围得到一个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';"

2 个答案:

答案 0 :(得分:4)

您的ORDER BY语句不能存在。将其移至最后

我还会给出强制性的“不要这样做”的演讲。像这样连接SQL字符串会让您受到SQL注入攻击。在SO和Google上有大量有关这方面的信息,所以我不打算参与其中,但你一定要考虑将其作为参数化查询。

答案 1 :(得分:0)

就像他说的那样......你的订单条款出了问题:)

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; 

我还要注意,Microsoft(http://technet.microsoft.com/en-us/library/ms190387(v=sql.105).aspx)建议使用模式限定对象。您还应该在top(value)语句周围使用括号。

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;