将选择查询更改为更新

时间:2014-07-10 10:49:21

标签: sql sql-update

我无法将以下选择查询更改为更新查询。请有人帮忙

SELECT 
CONVERT(varchar(10), (ROW_NUMBER() over (order by (select null)))) + 'Test@' +(SELECT SUBSTRING(Email, CHARINDEX('@', Email) + 1, LEN(Email) - CHARINDEX('@', Email))) as Email
,CONVERT(varchar(10), (ROW_NUMBER() over (order by (select null)))) + 'Media' as [Last Name]
from dbo.MPP_Inserts as MT

我已尝试过以下内容但收到错误消息:

  

窗口函数可以通过子句出现在选择或顺序中)

Update dbo.MPP_Inserts
Set Email = CONVERT(varchar(10), (ROW_NUMBER() over (order by (select null)))) + 'Test@' +(SELECT SUBSTRING(Email, CHARINDEX('@', Email) + 1, LEN(Email) - CHARINDEX('@', Email)))
, [Last Name] = CONVERT(varchar(10), (ROW_NUMBER() over (order by (select null)))) + 'DMG Media' 

1 个答案:

答案 0 :(得分:1)

看起来您正在使用SQL Server。如果是这样,您有可更新的CTE:

with toupdate as (
    SELECT mt.*,
           CONVERT(varchar(10), (ROW_NUMBER() over (order by (select null)))) + 'Test@' +(SELECT SUBSTRING(Email, CHARINDEX('@', Email) + 1, LEN(Email) - CHARINDEX('@', Email))) as new_Email,
           CONVERT(varchar(10), (ROW_NUMBER() over (order by (select null)))) + 'Media' as new_lastname
    from dbo.MPP_Inserts MT
   )
update toupdate
    Set Email = new_email,
       [Last Name] = new_lastname;

子串中的嵌套select是完全没必要的,但我保留了表达式不变,因此它们与查询中的相同。但是,new_email可以表示为:

CONVERT(varchar(10), (ROW_NUMBER() over (order by (select null)))) + 'Test@' +SUBSTRING(Email, CHARINDEX('@', Email) + 1, LEN(Email) - CHARINDEX('@', Email)) as new_Email,