除了這個事實,這是不好的設計,這裏是一個解決方案:
就在這個粘貼到一個空的查詢窗口,然後執行。適應您的需求...
declare @tbl TABLE(Column1 VARCHAR(15),Column2 VARCHAR(15),Column3 VARCHAR(150));
INSERT INTO @tbl VALUES
('ABC','123','User7;User9')
,('nbm','qre','User1;User2;User3')
,('POI','kjh','User1;User4;User5;User9');
WITH Splitted AS
(
SELECT Column1,Column2,CAST('<x>'+REPLACE(Column3,';','</x><x>')+'</x>' AS XML) AS Col3Splitted
FROM @tbl
)
SELECT Column1,Column2,Col3Splitted
,Col3Splitted.value('x[1]','varchar(max)') AS Column4
,Col3Splitted.value('x[2]','varchar(max)') AS Column5
,Col3Splitted.value('x[3]','varchar(max)') AS Column6
,Col3Splitted.value('x[4]','varchar(max)') AS Column7
/*Add as many as you need*/
FROM Splitted
在與@SeanLang的討論後,我添加這種動態的方法。它將計算Column3中分號的最高數量,並動態構建上面的語句。
CREATE TABLE #tbl (Column1 VARCHAR(15),Column2 VARCHAR(15),Column3 VARCHAR(150));
INSERT INTO #tbl VALUES
('ABC','123','User7;User9')
,('nbm','qre','User1;User2;User3')
,('POI','kjh','User1;User4;User5;User9');
DECLARE @sql VARCHAR(MAX)=
'WITH Splitted AS
(
SELECT Column1,Column2,CAST(''<x>''+REPLACE(Column3,'';'',''</x><x>'')+''</x>'' AS XML) AS Col3Splitted
FROM #tbl
)
SELECT Column1,Column2';
DECLARE @counter INT = 0;
WHILE @counter<=(SELECT MAX(LEN(Column3) - LEN(REPLACE(Column3, ';', ''))) from #tbl)
BEGIN
SET @[email protected]+1;
SET @[email protected]+',Col3Splitted.value(''x[' + CAST(@counter AS VARCHAR(10)) + ']'',''varchar(max)'') AS Column' + CAST(@counter+3 AS VARCHAR(10));
END
SET @[email protected]+ ' FROM Splitted;';
EXEC (@sql);
DROP TABLE #tbl;
是否有你需要在同一個表中的用戶的原因?爲什麼不把它們分離到另一個表中,然後創建一個鏈接表來加入它們?這樣你就不用太擔心會有多少用戶...... –
你實際上是想修改包含數據的表結構還是僅僅用於顯示目的? – DeanOC
您遇到問題的原因是因爲您的數據未正確歸一化。您首先必須將該分隔列表拆分爲可用的東西。然後,您將需要一個動態交叉表或數據透視表來生成您所需的動態列。 –