我在Table1中有幾個字符串,我想根據表2中的值進行更新。SQL Server拼圖 - 在逗號之前複製逗號並替換字符串?
示例代碼
http://rextester.com/HQFOQ18215
IF OBJECT_ID('Test1','U') iS NOT NULL
DROP TABLE Test1;
IF OBJECT_ID('Test2','U') iS NOT NULL
DROP TABLE Test2;
Create table Test1
(
Id INT
,Lid INT
,MyString VARCHAR(MAX)
,Did INT
,Secid INT
);
INSERT INTO Test1 values (1,100,'you,shall,not,pass,gandlaf,the,grey', 401, 501);
INSERT INTO Test1 values (2,100,'ok,fine,bye', 401, 501);
INSERT INTO Test1 values (3,100,'test,dev,uat,prod', 403, 501);
INSERT INTO Test1 values (4,100,'1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16', 404, 501);
Create table Test2
(
Id INT IDENTITY(1,1)
,SecId INT
,CommaPosition INT
,Value VARCHAR(50)
,Did INT
,RowId INT
);
INSERT INTO Test2 Values (501, 4, '[Quantity]', 401, 1);
INSERT INTO Test2 Values (501, 14, '[Price]', 401, 1);
INSERT INTO Test2 Values (501, 4, '[Quantity]', 401, 2);
INSERT INTO Test2 Values (501, 14, '[Price]', 401, 2);
INSERT INTO Test2 Values (501, 14, '[Quantity|Price]', 403, 3);
INSERT INTO Test2 Values (501, 4, '[Interest]', 404, 4);
INSERT INTO Test2 Values (501, 14, '[Expired]', 404, 4);
SELECT * FROM Test1;
SELECT * FROM Test2;
期望輸出
/*
Expected OUTPUT
Id Lid MyString Did Secid
1 100 you,shall,not,[quantity],gandlaf,the,grey,,,,,,,[Price], 401 501
2 100 ok,fine,bye,[quantity],,,,,,,,,,[Price], 402 501
3 100 test,dev,uat,prod,,,,,,,,,,[Quantity|Price], 403 501
4 100 1,2,3,[Quantity],5,6,7,8,9,10,11,12,13,[Price],15,16 404 501
*/
第一串
you,shall,not,pass,gandlaf,the,grey
其中"pass"
是之前其通過[quantity]
從表2但是這並未替換第四逗號位置't h ave第14個逗號 所以逗號被複制直到它到達第14個逗號並且在第14個逗號[Price]
被替換之前。最終輸出是"you,shall,not,[quantity],gandlaf,the,grey,,,,,,,[Price],"
第二個字符串
ok,fine,bye
沒有逗號第四十四任逗號,所以第4逗號添加和[quantity]
之前在表2和最終被取代,然後加逗號,直到第14位的逗號位置列 BASD字符串將成爲ok,fine,bye,[quantity],,,,,,,,,,[Price],
三串
test,dev,uat,prod
只有14逗號位置表2中可用,因此逗號被複制,直到14日逗號和14逗號之前[Quantity|Price]
串 加入最終的字符串變成test,dev,uat,prod,,,,,,,,,,[Quantity|Price],
在第四根弦
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
如果你看到第4和第14次成爲逗號可用,因此14日逗號之前的字符串被替換[Interest]
和字符串成爲14逗號被[Expired]
替換而將餘下的字符串不變。
我想實現上面的輸出,我試過下面的update語句沒有給我想要的結果。
UPDATE T1
SET T1.MyString = T1.MyString + REPLICATE(',',T2.CommaPosition - (len(T1.MyString) - LEN(REPLACE(T1.MyString,',',''))))
FROM Test1 as T1 INNER JOIN Test2 as T2 ON T1.Secid = T2.SecId AND T1.Did = T2.Did AND T1.Id = T2.RowId;
SELECT DISTINCT T1.Lid, T1.MyString, T1.Did, T1.Secid, T2.RowId
FROM Test1 as T1 INNER JOIN Test2 as T2 ON T1.Secid = T2.SecId AND T1.Did = T2.Did AND T1.Id = T2.RowId;
這根本沒有任何意義。爲什麼你首先有這些奇怪的分隔字符串?這違反了1NF並且破壞了關係數據的整個觀點。 –