即使语法错误,SQL查询仍然有效

时间:2014-08-28 07:47:47

标签: sql sql-server sql-server-2008

我在存储过程中运行SQL查询,如下面的

SELECT 
    t1.id,t2.Name
FROM 
    table1 t1 , table2 t2 ,table2 t3,table4 t4
WHERE 
    t1.id=t3.t4.id

此查询在与SQL Server 2000兼容时在SQL Server 2008上执行,但如果我们关闭与SQL Server 2000的兼容性,则此Query会出现预期的语法错误。 有人可以帮我理解为什么会这样吗?提前谢谢


原始查询:

SELECT
      ConfigID , LocationDesc + '-' + LOBTeamDesc LocLOBTeamSource
FROM Config CONFIG , Location_LOBTeam LOCLOB , Location LOC , LOBTeam LOB, System SRC
WHERE CONFIG.LocationLOBTeamID = LOC.LOB.LocationLOBTeamID
      AND CONFIG.SourceSystemID = SRC.SystemID
      AND LOCLOB.LocationID = LOC.LocationID
      AND LOCLOB.LOBTeamID = LOB.LOBTeamID
      AND (GETDATE() BETWEEN CONFIG.effectiveDate AND CONFIG.EndDate
      OR CONFIG.EndDate IS NULL)
ORDER BY
      LOC.LocationCode

2 个答案:

答案 0 :(得分:0)

我认为应用当前标准连接语法的原始查询将是:

SELECT
      ConfigID
    , LocationDesc + '-' + LOBTeamDesc LocLOBTeamSource
FROM Config CONFIG
      INNER JOIN Location_LOBTeam LOCLOB
                  ON CONFIG.LocationLOBTeamID = LOCLOB.LocationLOBTeamID
      INNER JOIN Location LOC
                  ON LOCLOB.LocationID = LOC.LocationID
      INNER JOIN LOBTeam LOB
                  ON LOCLOB.LOBTeamID = LOB.LOBTeamID
      INNER JOIN [System] SRC
                  ON CONFIG.SourceSystemID = SRC.SystemID
WHERE (GETDATE() BETWEEN CONFIG.effectiveDate AND CONFIG.EndDate
      OR CONFIG.EndDate IS NULL)
ORDER BY
      LOC.LocationCode

也许这会有所帮助。

+ EDIT "系统"作为表名,这可能是个问题吗?建议你尝试[系统]

+ EDIT2 原文是这样的:LOC.LOB.LocationLOBTeamID,但这似乎是一个错误,因为有一个别名LOCLOB

答案 1 :(得分:0)

我想msdn的帖子回答了这个问题Compatibility Levels and Stored Procedures

在上面的帖子中,“兼容级别80和级别90之间的差异”部分下的第3点指出“WHEN将ORDER BY列表中的列引用绑定到SELECT列表中定义的列,忽略列歧义并列有时会忽略前缀。这可能导致结果集以意外顺序返回。“ 在我的数据库上,我使用兼容级别80,即2000,这就是为什么它使用给定的语法顺利运行,但当我删除此兼容性并使其为100,即2008 / R2脚本提供预期的语法错误