How to perform split operation on strings and attach to specific ids using SQL SERVER 2000(Without cursor)?
I have a table wuth the folowing structure
PickupPointCode LocationCode ClientCode
1 LOC1 Client1/Client2
2 LOC2 Client3/Client4/Client5
3 LOC3 Client6
The desired output being
PickupPointCode LocationCode ClientCode
1 LOC1 Client1
1 LOC1 Client2
2 LOC2 Client3
2 LOC2 Client4
2 LOC2 Client5
3 LOC3 Client6
Usin开发者_如何学JAVAg SQL serevr 2005 I wrote the below query to get this done
;WITH cte AS (
SELECT
PickupPointCode
,LocationCode
,CAST('<i>' + REPLACE(ClientCode, '/', '</i><i>') + '</i>' AS XML) AS ClientCodes
FROM <TABLE NAME>)
SELECT
PickupPointCode
,LocationCode
,x.i.value('.', 'VARCHAR(MAX)') AS ClientCode
FROM cte
CROSS APPLY ClientCodes.nodes('//i') x(i)
But now I have to do the same thing using SQL SERVER 2000. How can I perform the same?
Thanks
The basic idea is to multiply each row as many times as there are CLIENTs. Then, extract the appropriate part of the string.
Have a look at some example queries that work on SQL2005+ here.
You will need to work with an extra table that contains sequential numbers in SQL2000.
CREATE TABLE dbo.Numbers
(
N INT NOT NULL PRIMARY KEY
);
GO
DECLARE @rows AS INT;
SET @rows = 1;
INSERT INTO dbo.Numbers VALUES(1);
WHILE(@rows <= 1000)
BEGIN
INSERT INTO dbo.Numbers SELECT N + @rows FROM dbo.Numbers;
SET @rows = @rows * 2;
END
This is the numbers table you can join onto. And below is the query that should work on SQL 2000.
SELECT PickupPointCode, LocationCode,
SUBSTRING(ClientCode, Numbers.N,
CHARINDEX('/', ClientCode + '/', Numbers.N) - Numbers.N) AS ClientCode
FROM <TABLE_NAME>
JOIN Numbers ON Numbers.N <= DATALENGTH(ClientCode) + 1
AND SUBSTRING('/' + ClientCode, Numbers.N, 1) = '/'
精彩评论