复制代码 代码如下:
--建一个表
CREATE TABLE MyData
(
ids INT IDENTITY PRIMARY KEY,
Data NVARCHAR(1000)
)
go
--插入测试数据
INSERT INTO MyData VALUES('')
INSERT INTO MyData VALUES('a,b,c')
INSERT INTO MyData VALUES('q')
INSERT INTO MyData VALUES('i,p')
GO
select * from MyData
go
--查询结果
ids Data
1
2 a,b,c
3 q
4 i,p
复制代码 代码如下:
create FUNCTION fun_MyData(
@data AS NVARCHAR(1000)
)
RETURNS @tem TABLE( id INT , value nvarchar(100) )
AS
BEGIN
select @data=isnull(@data,'')
if len(@data)=0
return --字符长度为0 ,退出
declare @id AS INT
select @id=1
declare @end AS INT
select @end = CHARINDEX(',', @data)
while(@end>0)
begin
insert into @tem(id,value)
select @id,left(@data,@end-1)
select @id=@id+1
select @data=right(@data,len(@data)-@end)
select @end = CHARINDEX(',', @data)
end
if len(@data)>0
begin
insert into @tem(id,value)
select @id,@data
end
RETURN
END
复制代码 代码如下:
SELECT m.ids, f.*
FROM MyData m CROSS APPLY fun_MyData(data) f
go
--结果
ids id value
2 1 a
2 2 b
2 3 c
3 1 q
4 1 i
4 2 p
SELECT m.ids, f.*
FROM MyData m OUTER APPLY fun_MyData(data) f
go
--结果
ids id value
1 NULL NULL
2 1 a
2 2 b
2 3 c
3 1 q
4 1 i
4 2 p
复制代码 代码如下:
--sql2000版本
declare @ids int
select @ids =0
declare @data nvarchar(200)
select @data=''
--定义表变量临时存放数据
declare @tem table(
ids int,
id int,
value nvarchar(100)
)
DECLARE test_cursor CURSOR FOR
SELECT ids, Data FROM MyData
OPEN test_cursor
FETCH NEXT FROM test_cursor
INTO @ids,@data
WHILE @@FETCH_STATUS = 0
begin
insert into @tem
select @ids,id,value
from dbo.fun_MyData(@data)
FETCH NEXT FROM test_cursor
INTO @ids,@data
end
CLOSE test_cursor
DEALLOCATE test_cursor
select * from @tem
新闻热点
疑难解答