是否可以重構此語句以刪除子查詢? (Is it possible to refactor this statement to remove the subquery?)


問題描述

是否可以重構此語句以刪除子查詢? (Is it possible to refactor this statement to remove the subquery?)

I'm trying to take data from one column, MyTable.SSN, and copy it to another in the same table, MyTable.SSNWithDashes, just formatted differently.  If MyTable.SSN doesn't have exactly 9 digits, I don't care to process it at all.

I've tried this:

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

While this works, it throws an error:

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

While I do understand what the warning is saying, I'm not really sure how to go about this differently.

How can I refactor this to remove that warning (and perhaps read a little cleaner)?

‑‑‑‑‑

參考解法

方法 1:

UPDATE dbo.[MyTable] 
  SET [SSNWithDashes] = CASE
  WHEN LEN(SSN) = 9 THEN 
    LEFT([SSN],3) + '‑' + SUBSTRING([SSN],4,2) + '‑' + RIGHT([SSN],4) 
  ELSE NULL
END;

方法 2:

Assuming your SSNWithDashes is already NULL then

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

Every other rows remain NULL

(by CypherAaron Bertrandcodingbiz)

參考文件

  1. Is it possible to refactor this statement to remove the subquery? (CC BY‑SA 3.0/4.0)

#sql-server-2005 #tsql






相關問題

可更新查詢所需的最低權限 (Access Project) (Minimum permissions required for an updatable query (Access Project))

Sql中的WHERE,結合兩個快速條件會成倍增加成本 (WHERE in Sql, combining two fast conditions multiplies costs many times)

是否可以重構此語句以刪除子查詢? (Is it possible to refactor this statement to remove the subquery?)

Không gửi được tệp nhật ký bằng 'Tác vụ Gửi Thư' từ trình xử lý OnError (Sending the log file using a 'Send Mail Task' from the OnError handler fails)

擴展 SSRS 中的圖表功能 (Extending chart functionality in SSRS)

sql server 2005 數據庫郵件錯誤(操作已超時) (sql server 2005 database mail error (The operation has timed out))

從.NET應用程序到SQL Server的緩慢調用 (Sporadically Slow Calls From .NET Application To SQL Server)

我需要在 sql 中獲取 alldata whereclause? (i need to get alldata whereclause in sql?)

一種檢查 SQL 2005 中是否存在外鍵的方法 (A way to check if foreign key exists in SQL 2005)

如何在 SSIS 中調用存儲過程? (How do you call a Stored Procedure in SSIS?)

什麼會使桌子“變慢”? (What would make a table "slow?")

可以在這裡使用 Common Table 表達式來提高性能嗎? (Can Common Table expressions be used here for performance?)







留言討論