[SQL Fiddle][1]
--------------------------------------------------------
--create temp table for using in split
IF OBJECT_ID('tempdb..#Tally') IS NOT NULL
DROP TABLE #Tally
CREATE TABLE #Tally (N INT)
DECLARE @i AS INT = 1
WHILE @i != 1000
BEGIN
INSERT INTO #Tally
(N)
VALUES (@i)
SET @i = @i + 1
END
--------------------------------------------------------
--Create temp table EmployeeMst
IF OBJECT_ID('tempdb..#EmployeeMst') IS NOT NULL
DROP TABLE #EmployeeMst
CREATE TABLE #EmployeeMst
(
SrNo INT ,
EmpNo VARCHAR(10),
)
INSERT INTO #EmployeeMst
VALUES (1, 'abc'),
(2, 'xyz'),
(3, 'pqr'),
(4, 'def')
--------------------------------------------------------
--Create temp table EmployeeCity
IF OBJECT_ID('tempdb..#EmployeeCity') IS NOT NULL
DROP TABLE #EmployeeCity
CREATE TABLE #EmployeeCity
(
srno INT ,
City VARCHAR(20) ,
EmplSrNo VARCHAR(MAX)
)
INSERT INTO #EmployeeCity
VALUES (1, 'Delhi', '1,2,3,4'),
(2, 'Mumbai', '2,3,1'),
(3, 'New York', '3,2')
--------------------------------------------------------
--Get output as in example
;
WITH EmployeeCityUpdated
AS (SELECT E.srno ,
E.City ,
CONVERT(INT, REPLACE(f4.EmpNoUpd, ',', '')) AS EmployeeName
FROM #EmployeeCity AS E
JOIN #Tally AS T ON SUBSTRING(',' + E.EmplSrNo, T.N, 1) = ','
AND T.N < LEN(EmplSrNo) + 1
CROSS APPLY (SELECT string = SUBSTRING(' '
+ EmplSrNo + ',',
T.N + 1,
LEN(EmplSrNo)
+ 1)
) f1
CROSS APPLY (SELECT p1 = CHARINDEX(',', string)
) f2
CROSS APPLY (SELECT EmpNoUpd = SUBSTRING(EmplSrNo,
T.N, p1)
) f4
)
SELECT EC.srno ,
EC.City ,
SUBSTRING((SELECT ',' + CONVERT(VARCHAR, EM.EmpNo)
FROM EmployeeCityUpdated AS ECU
JOIN #EmployeeMst AS EM ON ECU.EmployeeName = EM.SrNo
WHERE ECU.srno = EC.srno
FOR
XML PATH('')
), 2, 1000) AS EmployeeName
FROM #EmployeeCity AS EC
--------------------------------------------------------
--srno City EmployeeName
--1 Delhi abc,xyz,pqr,def
--2 Mumbai xyz,pqr,abc
--3 New York pqr,xyz
這是非常不好的數據庫設計,你能夠改變它嗎? – DavidG 2014-12-02 11:56:25
通過使用聯結表來修復數據庫設計,而不是嘗試進行此項工作。 – 2014-12-02 11:56:49
是的,我可以改變,但這是舊錶,所以我只能使用這張表 – 2014-12-02 11:57:25