我在SQL Server中有一个包含
等数据的表ID Name Des
1 A Text1, Text2
2 B Text3, Text4
需要选择语句来获取如下数据:
ID Name Des
1 A Text1
1 A Text2
2 B Text3
2 B Text4
答案 0 :(得分:2)
您可以使用Split
- 函数,该函数也适用于SQL-Server 2005(我正在使用):
CREATE FUNCTION [dbo].[Split]
(
@ItemList NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @ItemTable TABLE (Item VARCHAR(250))
AS
BEGIN
DECLARE @tempItemList NVARCHAR(MAX)
SET @tempItemList = @ItemList
DECLARE @i INT
DECLARE @Item NVARCHAR(4000)
SET @i = CHARINDEX(@delimiter, @tempItemList)
WHILE (LEN(@tempItemList) > 0)
BEGIN
IF @i = 0
SET @Item = @tempItemList
ELSE
SET @Item = LEFT(@tempItemList, @i - 1)
INSERT INTO @ItemTable(Item) VALUES(@Item)
IF @i = 0
SET @tempItemList = ''
ELSE
SET @tempItemList = RIGHT(@tempItemList, LEN(@tempItemList) - @i)
SET @i = CHARINDEX(@delimiter, @tempItemList)
END
RETURN
END
然后此查询返回结果:
SELECT ID,
Name,
Split.Item AS Des
FROM dbo.TableName t
CROSS APPLY [dbo].[Split](t.Des, ',') Split
答案 1 :(得分:0)
试试这个,
select id,name,substr(Des,0,instr(Des,1)) as des
from TableName
union
select id,name,substr(Des,instr(Des,1)+1) as des
from TableName