SQL单独行

时间:2014-02-20 14:44:38

标签: sql sql-server-2008

我的表ABC包含如下数据:

ID  Data
1   text|text|text
2   text|text|text

查询是什么,所以我得到以下结果?

ID  Data
1   text
1   text
1   text
2   text
2   text
2   text

Code可能是正确的方法吗?如何使用它以便获取数据记录的ID?

2 个答案:

答案 0 :(得分:2)

Upto SQL Server 2008 R2 我认为,我们没有比这更好的选择,但在SQL Server 2012中有一些额外的附加功能可能是可能的。

DECLARE @tblTemp TABLE
(
ID INT
, TextValue NVARCHAR(500)
)

INSERT INTO @tblTemp
SELECT 1,   'text|text|text'
UNION
SELECT 2,   'text|text|text'

SELECT * FROM @tblTemp

DECLARE 
@ID INT,
@Data NVARCHAR(MAX),
@Expression NVARCHAR(5);

DECLARE @Temp TABLE 
(
ID INT,
Data NVARCHAR(100)
) 


DECLARE TempCursor CURSOR FORWARD_ONLY STATIC FOR
SELECT ID, TextValue, '|' FROM @tblTemp 

-- Open cursor and try to fetch first element
OPEN TempCursor
FETCH NEXT FROM TempCursor INTO @ID, @Data, @Expression

-- loop while fetch returned next item
WHILE @@FETCH_STATUS = 0
BEGIN

    -- Do the processing
    DECLARE @Index INT
    SET @Index = 1

    WHILE (CHARINDEX(@Expression, @Data) > 0)
    BEGIN
        INSERT INTO @Temp(ID, data)
        SELECT @ID, Data = LTRIM(RTRIM(SUBSTRING(@Data, 1, CHARINDEX(@Expression, @Data)-1)))

        SET @Data = SUBSTRING(@Data, CHARINDEX(@Expression, @Data) + 1, LEN(@Data))
        SET @Index = @Index + 1
    END

    INSERT INTO @Temp (ID, Data)
    SELECT @ID, Data = LTRIM(RTRIM(@Data))

    -- fetch next entry
    FETCH NEXT FROM TempCursor INTO @ID, @Data, @Expression
END

-- Close and deallocate cursor
CLOSE TempCursor
DEALLOCATE TempCursor

SELECT DISTINCT * FROM @Temp

答案 1 :(得分:0)

亲爱的朋友创建sql函数然后调用它

CreateFUNCTION [dbo].[SplitTest](@String varchar(MAX), @Delimiter char(1))    
as 
begin 
declare @idx int       
declare @slice varchar(8000)       

select @idx = 1       
    if len(@String)<1 or @String is null  return       

while @idx!= 0       
begin       
    set @idx = charindex(@Delimiter,@String)       
    if @idx!=0       
        set @slice = left(@String,@idx - 1)       
    else       
        set @slice = @String       

    if(len(@slice)>0)  
        insert into @temptable(Items) values(@slice)       

    set @String = right(@String,len(@String) - @idx)       
    if len(@String) = 0 break       
end   
return  
end;

Select ID, SplitTest(Data,'|') From YourTable