我已經繼承了設置不佳的數據源。鑑於目前的數據結構:SQL將列的一部分複製到新列中
PreAddress City County 12312 Osprey Drive NW Gig Harbor NULL NULL 12312 Osprey Drive NW Gig Harbor NULL NULL 3022 SW Bradford St Seattle NULL NULL 3022 SW Bradford St Seattle NULL NULL 4605 Prestwick Lane SE Olympia NULL NULL 921 129th Street Court East Tacoma Auburn/Pierce NULL NULL
我需要拆掉的城市名稱了前置地址欄,並在市列傾倒,所以它看起來像:
PreAddress City County 12312 Osprey Drive NW Gig Harbor NULL 12312 Osprey Drive NW Gig Harbor NULL 3022 SW Bradford St Seattle NULL 3022 SW Bradford St Seattle NULL 4605 Prestwick Lane SE Olympia NULL 921 129th Street Court East Tacoma Auburn/Pierce NULL
任何SQL大師那裏有什麼想法如何腳本?
UPDATE
首次通過SQL:
USE [SMS]
GO
IF OBJECT_ID('tempdb..#tmpCitiesCounties') IS NOT NULL
DROP TABLE #tmpCitiesCounties
GO
IF OBJECT_ID('tempdb..#tmpCityCleanup') IS NOT NULL
DROP TABLE #tmpCityCleanup
GO
CREATE TABLE #tmpCitiesCounties
([ccId] INT IDENTITY(1, 1)
PRIMARY KEY
, [City] VARCHAR(50) NOT NULL
, [County] VARCHAR(50) NOT NULL);
CREATE TABLE #tmpCityCleanup
([Id] INT NULL
, [Address] VARCHAR(64) NULL
, [City] VARCHAR(50) NULL
, [County] VARCHAR(50) NULL);
INSERT INTO [#tmpCitiesCounties]
([City], [County])
VALUES ('Battle Ground', 'Clark'),
('Camas', 'Clark'),
('La Center', 'Clark'),
('Ridgefield', 'Clark'),
('Vancouver', 'Clark'),
('Washougal', 'Clark'),
('Yacolt', 'Clark'),
('Fircrest', 'Pierce'),
('Gig Harbor', 'Pierce'),
('Unincorporated', 'Skagit'),
('Arlington', 'Snohomish'),
('Bothell/Snohomish', 'Snohomish');
INSERT INTO [#tmpCityCleanup]
SELECT [SNPR].[Id]
, REPLACE(LOWER([SNPR].[PreAddress]), LOWER([TCC].[City]), '') AS [Address After]
, [TCC].[City]
, [TCC].[County]
FROM [dbo].[SellerNetProceedsResult] AS SNPR
LEFT JOIN [#tmpCitiesCounties] AS TCC
ON [TCC].[City] = RIGHT(LOWER([SNPR].[PreAddress]), LEN(LOWER([TCC].[City])))
ORDER BY [SNPR].[Id] DESC
SELECT [TCC1].[Id]
, [TCC1].[Address]
, [TCC1].[City]
, [TCC1].[County]
FROM [#tmpCityCleanup] AS TCC1
所以,這個塊SQL的正確眼淚的東西出來(市,縣的該臨時表將被截斷,因爲有超過了很多我想寫在這篇文章中),但正如上面那行有「Tacoma Auburn/Pierce」的行一樣,上面的SQL在刪除「Auburn/Pierce」後留下了「Tacoma」。
如果我再運行下面的SQL代碼,我得到的地址在兩個表之間不承認:
SELECT [TCC1].*
, REPLACE([TCC1].[Address], [TCC2].City, '') AS [Address After]
--, [TCC2].[City]
--, RIGHT([TCC1].[Address], LEN([TCC2].[City]))
FROM [#tmpCityCleanup] AS TCC1
left JOIN [#tmpCitiesCounties] AS TCC2
ON [TCC2].[City] = RIGHT([TCC1].[Address], LEN([TCC2].[City]))
相反,「地址後」一欄是空只。
Id PreAddress City CountyAddress After 151 12312 osprey drive nw Gig Harbor Algona King NULL 150 12312 osprey drive nw Gig Harbor Pierce NULL
也許我錯過了一些東西。
這其實是不遠處開來我一直在想這樣做的。我已經生成了與語句一起使用的臨時查找表變量。 – PKD
這種方法在「第一次通過」運行中效果很好,但第二次通過由於某種原因而變壞。儘管如此,我認爲這是正確的道路,並且會根據我的需要來做。謝謝! – PKD
你說的第二遍是什麼?由於您正在更新PreAddress字段(並取出城市),因此顯然它不會再匹配Cities表中的任何行。還是你的意思是別的? –