SQL UPDATE QUERY LOGIC

时间:2014-09-04 12:21:20

标签: sql sql-server tsql

Declare @identifier nvarchar(100),
        @identifier_New nvarchar(100)
Declare identifier cursor for  
    select distinct Identifier01 
    from update_rules 
    where Identifier01 is not null 
          and  Vendor='Bloomberg' 
          and [Geneva Code]='Geneva77'

open identifier

    fetch next from identifier into @identifier

    while @@fetch_status=0
    begin
        set @identifier_New=upper(substring(@identifier,2,len(@identifier)-2))

        if exists(select * from INFORMATION_SCHEMA.columns where table_name='investment' and column_name=@identifier_New)
        begin
            update i set i.[BBG Final Identifier]=case when u.Identifier01=@identifier then   @identifier_New    end
            FROM investment i,update_rules u
            where isnull(i.AType,'0')=isnull(u.[Asset Type],'0') and
                  isnull(i.IType,'0')=isnull(u.[Investment Type],'0') and 
                  isnull(i.Under_AType,'0')=isnull(u.[Under Lying Asset Type],'0') and 
                  isnull(i.Under_IType,'0')=isnull(u.[Under Lying Investment Type],'0') and
                  u.Vendor='Bloomberg' and u.[Geneva Code]='Geneva77'
        end
        fetch next from identifier into @identifier
    end
close identifier
deallocate identifier

我收到错误

update i set i.[BBG Final Identifier]=case when u.Identifier01=@**identifier** then   @identifier_New    end
    FROM investment i,update_rules u

1 个答案:

答案 0 :(得分:0)

这是您的查询:

       update i set i.[BBG Final Identifier]=case when u.Identifier01=@identifier then   @identifier_New    end
        FROM investment i, update_rules u
        where isnull(i.AType,'0')=isnull(u.[Asset Type],'0') and
              isnull(i.IType,'0')=isnull(u.[Investment Type],'0') and 
              isnull(i.Under_AType,'0')=isnull(u.[Under Lying Asset Type],'0') and 
              isnull(i.Under_IType,'0')=isnull(u.[Under Lying Investment Type],'0') and
              u.Vendor='Bloomberg' and u.[Geneva Code]='Geneva77';

首先,您应该使用显式join,而不是where子句中的隐式连接。 SQL Server仅允许从一个表进行更新,因此您不能在set的受让方一侧使用表别名。

尝试编写如下查询:

update i
    set [BBG Final Identifier] = (case when u.Identifier01 = @identifier
                                       then @identifier_New
                                  end)
    from investment i join
         update_rules u
         on isnull(i.AType,'0') = isnull(u.[Asset Type],'0') and
            isnull(i.IType,'0') = isnull(u.[Investment Type],'0') and 
            isnull(i.Under_AType,'0') = isnull(u.[Under Lying Asset Type],'0') and 
            isnull(i.Under_IType,'0') = isnull(u.[Under Lying Investment Type],'0')
    where u.Vendor='Bloomberg' and u.[Geneva Code]='Geneva77';