如何从CONCAT输出自动执行UPDATE语句

时间:2018-12-18 04:39:40

标签: sql sql-server

我有一个SQL查询,用于使用UPDATE来构建CONCAT语句。

示例:

select top 10000
  concat ('update customer set phone_number = ''',phone_number,
  ''' where id = ''',id,''';')
  from (
    select a.phone_number, c.id from customer c
    join address a on c.id = a.customer_id
    where c.phone_number is null
  ) as cust_phone;

结果:

update customer set phone_number = '628814232154' where id = '3';
update customer set phone_number = '62896631457' where id = '5';

是否可以使此UPDATE输出自动运行?我还是SQL编程的新手。

3 个答案:

答案 0 :(得分:1)

[假定sql-server]
如果您想使用Dynamic Sql路由,则几乎已发布的代码就在那里。您只需要将查询的输出连接到一个sql字符串中,然后使用Exec(@sql)

执行它即可。
declare @sql nvarchar(max)
select @sql = @sql + concat ('update customer set phone_number = ''',phone_number,''' 
    where id = ''',id,''';',Char(10))
from (
    select top 10000 a.phone_number, c.id from customer c
    join address a on c.id = a.customer_id
    where c.phone_number is null
) as cust_phone;

Exec(@sql)

您将需要像上面一样将前n个过滤器移到子查询中。

答案 1 :(得分:1)

为什么要建立一个字符串?

update c set phone_number = a.phone_number
from customer c
join address a on c.id = a.customer_id
where c.phone_number is null

如果您迫切需要在其中放置TOP:

update u set phone_number = t.phone_number
from customer u
join 
(
  select top 10000 c.id, a.phone_number 
  from customer c join address a on c.id = a.customer_id
  where c.phone_number is null
) t 
on u.id = t.id

答案 2 :(得分:0)

尝试:

UPDATE customer
SET phone_number = (SELECT phone_number
           FROM address
           WHERE customer.id = address.customer_id)
WHERE phone_number is null;