问题描述:
今天有一个朋友问我,他有如下一个表
RoleName | RoleList |
小明 | 1,2,3 |
希望能将RoleList中的1,2,3拆分成3列存储到数据库中。
此时我就想啦,这样拆分,确实有难度,函数函数不行,存储过程存储过程不行,那该怎么办呢?后来仔细想想,如果要是每行我能单独进行二次加工该多好啊。鉴于我这个想法,觉得游标可能适合我当前的问题。
因为游标可以单独循环每条记录,它不在有行的改练,而是有了列的概念,只要我循环每行数据,那么我就可以单独的对各个列进行一个操作,那具体的操作就可以人有我自己去实现啦,岂不乐哉。
最后代码如下:
IF (EXISTS ( SELECT
1
FROM
[sys].[objects] AS obj
WHERE
[obj].[name] = 'TBL_RoleList' ))
BEGIN
DROP TABLE TBL_RoleList
END
CREATE TABLE TBL_RoleList
(
[Name] NVARCHAR(10),
[RoleList] NVARCHAR(10)
)
INSERT INTO [dbo].[TBL_RoleList]
([Name], [RoleList])
VALUES
(N'小明', -- Name - nvarchar(10)
N'1,2,3' -- RoleList - nvarchar(10)
)
--SELECT * FROM [dbo].[TBL_RoleList]
IF (EXISTS ( SELECT
1
FROM
sys.objects AS obj
WHERE
obj.name = 'MyResult' ))
BEGIN
DROP TABLE MyResult
END
CREATE TABLE MyResult
(
name NVARCHAR(10),
id NVARCHAR(10)
)
DECLARE
@Name NVARCHAR(10),
@List NVARCHAR(100)
DECLARE My_Cursor CURSOR LOCAL
FOR
(SELECT
[rlist].[Name],
[rlist].[RoleList]
FROM
[dbo].[TBL_RoleList] AS rlist WITH (NOLOCK))
OPEN My_Cursor
FETCH NEXT FROM My_Cursor INTO @Name, @List
WHILE @@fetch_status = 0
BEGIN
DECLARE @id NVARCHAR(10)
DECLARE @index INT = CHARINDEX(',', @List, 1)
WHILE (@index <> 0)
BEGIN
SET @id = SUBSTRING(@list, 1, @index - 1)
INSERT INTO MyResult
VALUES
(@Name, @id)
SET @List = SUBSTRING(@list, @index + 1, LEN(@List))
SET @index = CHARINDEX(',', @List, 1)
IF @index = 0
BEGIN
INSERT INTO MyResult
VALUES
(@Name, @List)
BREAK
END
END
FETCH NEXT FROM My_Cursor INTO @Name, @List
END
CLOSE My_Cursor
DEALLOCATE My_Cursor
SELECT
*
FROM dbo.MyResult
来自为知笔记(Wiz)