I have two tables, Table1 and Table2, which have N no. of columns. I need to update Table1 based on Table2. I want to update all the columns in Table1 which are listed in a single column in Table2.
E.G
Table1 A B C D E . . .
1 2 3 4 5 . . .
7 6 5 4 3 . . .
Table2 X Y Col_Nam Col_Value
1 2 C 8
1 2 D 9
7 6 E 10
7 6 C 20
. . . .
. . . .
Update all the columns in Table1 which are listed in Table2 when matching the following condition Table1.A = Table2.X and Table1.B = Table2.Y
The Platform is SQL Server. What I am looking for is a solution which is dynamic, because I don't know the column names which I am going to update. Table1 can have N no. of columns which need to be updated. I tried the following using Cursor.
DECLARE @s Varchar(MAX), @key1 VARCHAR(MAX), @key2 VARCHAR(MAX), @Cname VARCHAR(MAX), @CValue VARCHAR(MAX)
DECLARE crs CURSOR FOR SELECT * FROM Table2
OPEN crs;
FETCH NEXT FROM crs inTO @key1,@key2,@Cname,@Cvalue;
WHILE @@FETCH_STATUS = 0
BEGIN
set @s =
'Update T1 SET ' + @FieldName + ' = ''' + @FieldValue +
''' from Table1 T1' +
' where T1.A = ''' + @key1 +
''' and T1.B = ''' + @key2
exec(@s)
FETCH NEXT FROM crs inTO @key1,@key2,@Cname,@Cvalue;
END
CLOSE crs
DEALLOCATE crs
Somehow it is not working and I want to put a default value for all those records which are not matching the where condition.
Any other solution or help will be appreciated.