如何在另一个查找表的帮助下更新表



我想执行一个数据库更改。我有两个表设置如下:查找是我创建的临时查找表。我还添加了一个名为cur_format的新列,但它是空的。

Currency
_______
[cur_format] [nchar](10) NULL,
[cur_format_old] [int] NULL
[other_data]  [int] NULL
cur_format_old   cur_format  other_data
0                             565656
1                             498985
2                             145126
3                             236124
2                             789565
4                             784512

Lookup
__________
[cur_format] [nchar](10) NULL,
[cur_format_old] [int] NULL
cur_format_old      cur_format
0                   USD
1                   GBP
2                   AUD
3                   CAD
4                   CNY

更新后,我希望货币表是这样的:

Currency
   ______
cur_format_old  cur_format    other_data
0               USD           565656
1               GBP           498985
2               AUD           145126
3               CAD           236124
2               AUD           789565
4               CNY           784512

查找表大约有100行。并且Currency表相当大,因此,我想使用脚本来更新表。如何在sql-server中实现这一点?非常感谢

我想你想要一个updatejoin:

update c
    set cur_format = l.cur_format
    from currency c join
         lookup l
         on c.cur_format_old = l.cur_format_old;

这将只更新两个表之间匹配的值

正如其他人所说,这没有任何意义。你似乎在对你的数据库进行非规范化。还需要注意的是,对于当前的数据类型,这将不起作用。把所有的理性考虑抛在脑后,做你要求做的事是可能的。同样,这对我来说似乎是一个非常糟糕的主意,但这里有一个完整的脚本,包括更改数据类型。

alter table Currency
    add NewFormat varchar(3)
update Currency
set NewFormat = l.cur_format
from Currency c
join MyLookup l on l.cur_format_old = c.cur_format

alter table Currency
    drop column cur_format
EXEC sp_rename 'Currency.NewFormat', 'cur_format', 'COLUMN';
select * from Currency

最新更新