我想更新数千行,但键入每个值都是耗时的
我的代码
UPDATE #table
SET city = 'New York'
WHERE city is null
AND store_id = '22'
预期结果
store_id city state
22 New york NY
22 New york NY
22 New york NY
33 LA CA
33 LA CA
如何修改代码,这样我就不必每次都输入“ New York”等内容?谢谢
答案 0 :(得分:1)
这就是我的想法,但是我相信可能会有更优化的方法来实现:
WITH cteCities(store_id, city, state) AS
(SELECT DISTINCT store_id, city, state FROM #table WHERE city IS NOT NULL)
UPDATE #table
SET city = cte.city, state = cte.state
FROM cteCities cte
INNER JOIN #table
ON cte.store_id = #table.store_id
WHERE #table.city IS NULL
答案 1 :(得分:0)
CREATE TABLE #t (store_id varchar(20),city varchar(20),[state] varchar(20))
INSERT INTO #t VALUES
('22', 'new', 'NY'),
('22', null, null),
('22', null, null),
('33', null, null),
('33', 'LA', 'CA')
;
WITH CTE AS
(
SELECT DISTINCT store_id, city, [state] FROM #t WHERE city IS NOT NULL
)
UPDATE #t
SET city = CTE.city, [state] = CTE.[state]
FROM CTE
INNER JOIN #t
ON CTE.store_id = #t.store_id
WHERE #t.city IS NULL