【发布时间】:2023-03-20 06:49:01
【问题描述】:
新手问题...寻找基于另一个表中是否存在值来更新新列的最快方法,同时替换值。
例如,下面将“Bought a car”和“car”放在另一个表中。问题是“买了车”在另一张桌子上。
我做了一个 hack 来重新选择值并进行替换,但是如果行更多,性能很糟糕,最多需要 3 到 5 分钟才能执行。
哦,SQL 大师,最好的方法是什么?
例子
DECLARE @Staging_Table TABLE
(
ACCTID INT IDENTITY(1,1),
NAME VARCHAR(50),
PURCHASES VARCHAR(255)
)
INSERT INTO @Staging_Table (Name, Purchases)
VALUES ('John','Bought a table')
INSERT INTO @Staging_Table (Name, Purchases)
VALUES ('Jack','Sold a car')
INSERT INTO @Staging_Table (Name, Purchases)
VALUES ('Mary','Returned a chair')
DECLARE @HISTORY TABLE
(
ACCTID INT IDENTITY(1,1),
NAME VARCHAR(50),
Item VARCHAR(255)
)
INSERT INTO @HISTORY (Name, Item)
VALUES ('John','')
INSERT INTO @HISTORY (Name, Item)
VALUES ('Jack','')
INSERT INTO @HISTORY (Name, Item)
VALUES ('Mary','')
UPDATE @HISTORY
Set ITEM = CASE WHEN EXISTS(
Select ts.Purchases as Output from @Staging_Table ts
where ts.NAME = Name AND ts.PURCHASES LIKE '%table%')
THEN REPLACE((Select ts2.PURCHASES Output
from @Staging_Table ts2 where ts2.NAME = Name AND ts2.PURCHASES LIKE '%table%'),'Bought a ','')
WHEN EXISTS(
Select ts.Purchases as Output from @Staging_Table ts
where ts.NAME = Name AND ts.PURCHASES LIKE '%car%')
THEN REPLACE((Select ts2.PURCHASES Output
from @Staging_Table ts2 where ts2.NAME = Name AND ts2.PURCHASES LIKE '%car%'),'Bought a ','')
End
SELECT * FROM @HISTORY
【问题讨论】:
标签: tsql replace case sql-like exists