新手问题...在替换值的同时,根据另一个表中存在的值来寻找更新新列的最快方法。
示例,下面,将“买车”和“汽车”一词带到另一张桌子上。问题是'买车'进入另一张桌子。
我做了一个黑客来重新选择值并进行替换,但是如果行数更多,性能非常糟糕,需要花费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
答案 0 :(得分:0)
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' ),
( 'Jack', 'Sold a car' ),
( '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', '' ),
( 'Jack', '' ),
( 'Mary', '' )
UPDATE L
SET L.ITEM = ( CASE WHEN R.PURCHASES LIKE '%table%'
THEN REPLACE(R.PURCHASES, 'Bought a ', '')
WHEN R.PURCHASES LIKE '%car%'
THEN REPLACE(R.PURCHASES, 'Sold a ', '')
END )
FROM @HISTORY AS L
JOIN @Staging_Table AS R ON L.NAME = R.NAME
WHERE ( R.PURCHASES LIKE '%table%'
OR R.PURCHASES LIKE '%car%'
)
SELECT *
FROM @HISTORY