SQL Server - 语法错误,靠近 )。

4

您能否请查看这段代码?我遇到了错误,但不确定是什么原因:

括号附近的语法有误。

select * 
from
    (select distinct 
         sar90.code, sar90.state, sar90.county, 
         sabet.code, sabet.state, sabet.county 
     from
         [dbo].[sarshomari_90] as sar90, 
         [dbo].[Fixed] as sabet 
     where 
         sar90.county = sabet.county 
         and sar90.state = sabet.state 
         and sar90.state = N'kerman')

2
不良习惯:使用旧式JOIN语句。旧式的“逗号分隔表列表”已经在20多年前被ANSI-92 SQL标准中更为“规范”的ANSI JOIN语法所取代,因此不建议使用。 - marc_s
我认为你应该自己尝试至少10分钟,我称之为SQL的早期错误。 - Neeraj Prasad Sharma
你怎么知道我没有呢? - Yousef
2个回答

7
您需要为子查询设置别名。但是,您不必使用子查询来实现。您可以直接使用SELECT DISTINCT。此外,请避免使用旧式的JOIN语法,应该使用明确的JOIN声明。
然而,如果您想使用子查询,您的列必须具有唯一名称。通过添加唯一的别名来实现这一点。
select *
from(
    select distinct
        sar90.code as code1, 
        sar90.state as state1,
        sar90.county as country1,
        sabet.code as code2,
        sabet.state as state2,
        sabet.county as country2
    from [dbo].[sarshomari_90] as sar90
    inner join [dbo].[Fixed] as sabet 
        on sar90.county = sabet.county 
        and sar90.state = sabet.state 
    where
        sar90.state = N'kerman'
)t

是的,我知道,但它是更大查询的一部分,我试图使用查询的较小部分。此外,别名无法工作,它会产生另一个错误。 - Yousef
@yousefyegane,您需要发布完整的代码以便我们帮助您。 - Madhivanan
你应该在子查询中为每个列使用唯一的别名。请查看我的编辑。 - Felix Pamittan

3

给子查询添加别名并给列添加别名以避免名称不明确。

select *
from
(select distinct
    [code1]   = sar90.code, 
    [state1]  = sar90.state,
    [county1] = sar90.county,
    [code2]   = sabet.code,
    [state2]  = sabet.state,
    [county2] = sabet.county
from [dbo].[sarshomari_90] as sar90, [dbo].[Fixed] as sabet
where sar90.county=sabet.county
      and sar90.state= sabet.state
      and sar90.state=N'kerman'AS tab

起初我使用AS,它报错如下: 列“state”在“fin”中被多次指定。 - Yousef

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接