在SQL Server中从TableB添加/更新TableA中最有效的方法是什么?

时间:2015-07-16 13:25:22

标签: sql sql-server sql-server-2012

我有两张桌子。表A有380列,基于TABLE_B中特定列的行值创建360列。当我向TABLE_B添加一个新行时,如果这不是TABLE_A中的列,则需要在TABLE_A中创建一个新列。

TABLE_A中的列是基于同一表中其他列的逻辑和另一个表TABLE_C的逻辑计算的。

以下查询需要一小时30分钟才能完成。

这种情况还有其他最佳解决方案吗?

我有以下查询,但需要大约一个半小时才能完成。

Declare @@columnname varchar(25)
DECLARE column_cursor cursor for
SELECT distinct [Column For Table_A] FROM [dbo].TABLE_B
OPEN column_cursor

FETCH NEXT FROM column_cursor
    INTO @columnname
        WHILE @@FETCH_STATUS = 0
            BEGIN
            set @starttime = GETDATE()
                if not exists (select * from sys.columns where Name = @columnname and object_id = object_ID('[TABLE_A]'))
                begin
                    SELECT @message =isnull(@columnname,'null column') +'  doesn''t exists, adding one'
                    Print @message
                    set @sqlquery  ='alter table [dbo].[TABLE_A] add ['+@columnname+'] decimal(20,5)'

                    Execute sp_executesql @sqlquery
                end
                set @sqlquery ='UPDATE [TABLE_A]
                                SET ['+@columnname+'] = [Amount]
                                where [value] = '''+@columnname+'''


                                UPDATE [TABLE_A]
                                SET  ['+@columnname+']  = (SELECT sum(total_au) totalusd from [TABLE_C] p
                                where [unique ID IC] = CONCAT([unique id],''-'','''+@columnname+''')
                                group by p.[unique ID]
                                )
                                where [value] <> '''+@columnname+'''
                                and ( ['+@columnname+'] = 0 Or ['+@columnname+'] is null)'

                Execute sp_executesql @sqlquery
            set @endtime = Getdate()
            set @elaspedtime =Datediff(second, @starttime, @endtime)
            PRINT   RIGHT('0' + CAST(@elaspedtime / 3600 AS VARCHAR),2) + ':' +
                    RIGHT('0' + CAST((@elaspedtime / 60) % 60 AS VARCHAR),2)  + ':' +
                    RIGHT('0' + CAST(@elaspedtime % 60 AS VARCHAR),2)

        FETCH NEXT FROM 
        column_cursor
        Into @columnname
    END
Close column_cursor
DEALLOCATE column_cursor

0 个答案:

没有答案