0

我正在尝试从一列中获取数据MyTable.SSN,并将其复制到同一张表中的另一列MyTable.SSNWithDashes,只是格式不同。如果MyTable.SSN不完全是 9 位数字,我根本不在乎处理它。

我试过这个:

IF( SELECT LEN( [SSN] ) FROM [MyTable] ) = 9
UPDATE [MyTable] SET [SSNWithDashes] = LEFT( [SSN], 3 ) + '-' + SUBSTRING( [SSN], 4, 2 ) + '-' + RIGHT( [SSN], 4 ) 
ELSE
UPDATE [MyTable] SET [SSNWithDashes] = NULL

虽然这有效,但它会引发错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

虽然我确实理解警告的意思,但我不确定如何以不同的方式解决这个问题。

我如何重构它以删除该警告(并且可能阅读更清晰)?

4

2 回答 2

4
UPDATE dbo.[MyTable] 
  SET [SSNWithDashes] = CASE
  WHEN LEN(SSN) = 9 THEN 
    LEFT([SSN],3) + '-' + SUBSTRING([SSN],4,2) + '-' + RIGHT([SSN],4) 
  ELSE NULL
END;
于 2012-08-29T00:26:52.593 回答
1

假设你SSNWithDashes已经是NULL那么

UPDATE dbo.[MyTable] 
  SET [SSNWithDashes]  = LEFT([SSN],3) + '-' + SUBSTRING([SSN],4,2) + '-' + RIGHT([SSN],4) 
WHERE LEN(SSN) = 9

每隔一行保留NULL

于 2012-08-29T00:31:21.120 回答