可以在update子句中使用select

时间:2014-12-29 14:06:41

标签: sql sql-update

我正在尝试使用select这样更新表。这是行不通的。这是正确的方法还是我必须将select的结果放入临时表并从中更新表?

Update WaterRevPropInfo
Set StreetDir = Direction
where exists (SELECT StreetNum,
ISNULL
( LTRIM
( RIGHT
( RTRIM(StreetNum),
LEN
( StreetNum
) +
1 -
( PATINDEX --Identifies first instance of a numeric char
( '%[0-9]%',
StreetNum
) +
PATINDEX --Identifies first instance of a non-numeric char
( '%[^0-9]%',
SUBSTRING --that follows the first numeric char
( StreetNum,
PATINDEX
( '%[0-9]%',
StreetNum
),
LEN(StreetNum)
) + ' '
)
) +
1
)
),
' '
) AS 'Direction')
FROM WaterRevPropInfo

1 个答案:

答案 0 :(得分:1)

如果TRUE至少有1行,则存在会为您WaterRevPropInfo提供,无论您在选择中放入什么内容。我想你需要做这样的事情:

UPDATE WaterRevPropInfo
SET    StreetDir = ISNULL(LTRIM(RIGHT(RTRIM(StreetNum), LEN(StreetNum) + 1 - (PATINDEX --Identifies first instance of a numeric char
       ('%[0-9]%', StreetNum) + PATINDEX                                               --Identifies first instance of a non-numeric char
       ('%[^0-9]%', SUBSTRING                                                          --that follows the first numeric char
       (StreetNum, PATINDEX ('%[0-9]%', StreetNum), LEN(StreetNum)) + ' ' ) ) + 1 ) ), StreetDir)

它会将您的所有逻辑分配给StreetDir,除非它是NULL,在这种情况下它会保留其值(将重新分配)。