Sql 如果记录为空,则添加值

Sql 如果记录为空,则添加值,sql,sql-server,sql-server-2005,Sql,Sql Server,Sql Server 2005,我有一个包含以下数据的表格: CUSIP SEDOL DESC 1111 NULL ABC Corp 1234 NULL ABCD Corp NULL 12 ABCDE Corp 现在,我在另一个数据库服务器上有另一个表: CUSIP SEDOL DESC 1111 18 ABC Corp 1234 19 ABCD Corp 1246 12 ABCDE Corp 如何根据不同数据库服务器中

我有一个包含以下数据的表格:

CUSIP   SEDOL   DESC
1111    NULL    ABC Corp
1234    NULL    ABCD Corp
NULL    12      ABCDE Corp
现在,我在另一个数据库服务器上有另一个表:

CUSIP   SEDOL   DESC
1111    18      ABC Corp
1234    19      ABCD Corp
1246    12      ABCDE Corp
如何根据不同数据库服务器中表中提供的值填充第一个表中的空值?(我正在使用SQL Server 2005)

您的问题不清楚
cusip
是否重要,因此您可能需要:

update table1 set
sedol = (select sedol from database2.table2 where cusip = table1.cusip)
where sedol is null;
要更新cusip,请使用以下命令:

update table1 set
cusip = (select cusip from database2.table2
         where desc = table1.desc
         and sedol = table2.sedol)
where cusip is null;
也许吧


首先根据Tim的评论添加链接服务器

然后,许多类似这样的查询都会依赖匹配规则

Update
  table1
Set
  Sedol = t2.Sedol
From
  table1 t1
    Inner Join
  server2.db2.schema2.table2 t2
    On t1.CusIP = t2.CusIP and t1.[Desc] = t2.[Desc] And t1.Sedol Is Null

添加链接服务器后,您的脚本将显示为

MERGE dbo.your_table AS target
USING [AnotherServer].dbo.your_table AS source
ON (target.[DESC] = source.[DESC])
WHEN MATCHED AND (target.CUSIP IS NULL OR target.SEDOL IS NULL)
  THEN UPDATE SET target.CUSIP = source.CUSIP,
                  target.SEDOL = source.SEDOL;

对于三个值,您最好只键入它们。或者再解释一下我们如何将一个匹配到另一个。SEDOL是独一无二的吗?库西普?SEDOL+DESC?任何两个部分的匹配都构成了一个匹配?我认为“不同数据库服务器中的表”是他的主要内容problem@Bohemian你能告诉我你对我的解决方案的看法吗?行吗?非常感谢您的反馈。@Аёёааааааааааааааа。您的查询可以工作,但它会更新每一行,并且(取决于内部优化)会为每一行运行子查询。删除
coalesce()。
where GoodTable.[CUSID]=BadTable.[CUSID]
update table1 t1
set t1.sedol 
   = coalesce (t1.sedol,(select top 1 sedol 
                     from table2 
                     where t1.cusip = cusip
                     and t1.desc = desc))
Update
  table1
Set
  Sedol = t2.Sedol
From
  table1 t1
    Inner Join
  server2.db2.schema2.table2 t2
    On t1.CusIP = t2.CusIP and t1.[Desc] = t2.[Desc] And t1.Sedol Is Null
MERGE dbo.your_table AS target
USING [AnotherServer].dbo.your_table AS source
ON (target.[DESC] = source.[DESC])
WHEN MATCHED AND (target.CUSIP IS NULL OR target.SEDOL IS NULL)
  THEN UPDATE SET target.CUSIP = source.CUSIP,
                  target.SEDOL = source.SEDOL;