So, I have this data that exists in a single column. Odd rows are ID, even rows are city. Is there a way to split this into two columns?
DECLARE @Data TABLE (
DataRow NVARCHAR(50)
)
INSERT INTO @Data VALUES
('1' )
, ('Albuquerque' )
, ('2' )
, ('Boston' )
, ('3' )
, ('Chicago' )
, ('4' )
, ('Dayton' )
, ('5' )
, ('Eumenclaw' )
, ('6' )
, ('Fresno' )
Right now I'm using the following code, but it seems like there should be a more efficient way using a pivot table.
DECLARE @DataID TABLE (
ID INT IDENTITY
, DataRow NVARCHAR(50)
)
INSERT INTO @DataID
SELECT * FROM @Data
DECLARE @CityData TABLE (
ID INT
, City NVARCHAR(100)
)
DECLARE @Counter INT = 0
, @ID INT
, @City NVARCHAR(50)
WHILE @Counter < (SELECT MAX(ID) / 2 FROM @DataID WHERE ID%2 = 0)
BEGIN
SET @Counter += 1
SET @ID = (SELECT CAST(DataRow AS INT) FROM @DataID WHERE ID = @Counter * 2 - 1)
SET @City = (SELECT DataRow FROM @DataID WHERE ID = @Counter * 2)
INSERT INTO @CityData
SELECT @ID, @City
END
SELECT * FROM @CityData
Results:
Oh, and apologies to those of you from Washington for the misspelling. And hopefully not New Mexico.