关键字“select”附近的语法不正确

时间:2010-09-10 21:26:48

标签: sql sql-server sql-server-2005 tsql

我有一组标准化不正确的表格,我正在尝试纠正这个问题。数据库是MS SQL 2005.

Table1有id字段(记录ID),mainID字段(人员ID)和sequence字段(以及确定排序顺序的int)

Table2有自己的id字段和一个人(sequence = 1)的第一条记录的id副本。

我已经向table2调用table2_id添加了一个新字段,我想用table2中的ID填充此字段,以便我可以取消table1.mainID。 table2仅包含每个人的一条记录的记录,mainId设置为table1.sequence = 1的ID。

这是我认为可以通过我收到错误来完成工作的更新查询

update table1 as a  
set regInfoID = (select b.id 
                 from table2 as b 
                 where b.ref1 = (select c.id 
                                 from table1 as c 
                                 where c.mainID = a.mainID 
                                       and sequence = 1))  

我认为自从下面的查询工作正常以来我就在正确的轨道上

select regInfoID = (select b.id 
                    from table2 as b 
                    where b.ref1 = (select c.id 
                                    from table1 as c 
                                    where c.mainID = a.mainID 
                                          and sequence = 1)), a.*  
from table1 as a  

3 个答案:

答案 0 :(得分:3)

我认为您的查询与此相同:

update a
set regInfoID = b.id
-- select a.*, b.id
from table2 b 
inner join table1 c on c.id = b.ref1
inner join table1 a on c.mainID = a.mainID and c.sequence = 1

从这个查询中,我认为您可能会有不确定的结果,因为table2(b)不能保证是单行结果。因此,regInfoID将设置为生成的b.id值之一。

答案 1 :(得分:0)

我想通了

update table1
set regInfoID = (select b.id 
                 from table2 as b 
                 where b.ref1 = (select c.id 
                                 from table1 as c 
                                 where c.mainID = a.mainID 
                                       and sequence = 1)) 
from table1 as a 

错误似乎是因为我在update语句中而不是在from语句中使用了alia。

感谢您的帮助。

答案 2 :(得分:0)

这是一种方法,使用有效的SELECT语句,并将其包装在CTE中:

with cte as (
    select a.*, _regInfoID = (select b.id 
                        from table2 as b 
                        where b.ref1 = (select c.id 
                                        from table1 as c 
                                        where c.mainID = a.mainID 
                                              and sequence = 1))
    from table1 as a 
    )
update cte set regInfoID = _regInfoID

我喜欢这种风格,因为您可以在应用之前预览修改,将SELECT转换为UPDATE

是微不足道的

但是你对原始查询的问题只是一个语法错误。这是应该如何编写的。请注意FROM table1 AS a

update a 
set regInfoID = (select b.id 
                 from table2 as b 
                 where b.ref1 = (select c.id 
                                 from table1 as c 
                                 where c.mainID = a.mainID 
                                       and sequence = 1))  
from table1 as a