

我的目的是 把 第一个表中的选择题选项 通过‘,’ 打散 通过第一个表的ID 和第二个表的OptionId做关联 ,把选项循环插入到第二个表中 Option中 希望用游标 能帮我实现楼
提示:选项的长度都是固定的 六个选择题;
sql?server,循环游标
------解决方案--------------------
更新还要帮你写不?
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-06 16:38:11
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] int,[tname] varchar(7),[toption] varchar(11))
insert [huang]
select 1,'选择题1','A,B,C,B,C,D' union all
select 2,'选择题2','A,B,C,B,C,D'
--------------开始查询--------------------------
select
id,
a.[tname],
SUBSTRING([toption],number,CHARINDEX(',',[toption]+',',number)-number) as [toption]
from
[huang] a,master..spt_values
where
number >=1 and number<=len([toption])
and type='p'
and substring(','+[toption],number,1)=','
----------------结果----------------------------
/*
id tname toption
----------- ------- -----------
1 选择题1 A
1 选择题1 B
1 选择题1 C
1 选择题1 B
1 选择题1 C
1 选择题1 D
2 选择题2 A
2 选择题2 B
2 选择题2 C
2 选择题2 B
2 选择题2 C
2 选择题2 D
*/
------解决方案--------------------
create table tab1
(id int,TName varchar(20),TOption varchar(20))
create table tab2
(Id int,TOptionId int,Options varchar(20))
insert into tab1
select 1,'选择题1','A,B,C,B,C,D' union all
select 2,'选择题2','A,B,C,B,C,D'
insert into tab2
select 1,1,null union all
select 2,1,null union all
select 3,1,null union all
select 4,1,null union all
select 5,1,null union all
select 6,1,null union all
select 7,2,null union all
select 8,2,null union all
select 9,2,null union all
select 10,2,null union all
select 11,2,null union all
select 12,2,null
-- 更新
update a
set a.Options=b.TOptions
from
(select TOptionId,Options,
row_number() over(partition by TOptionId order by Id) 'rn'
from tab2) a
inner join
(select a.id,
substring(a.TOption,b.number,charindex(',',a.TOption+',',b.number)-b.number) 'TOptions',
row_number() over(partition by a.id order by getdate()) 'rn'
from tab1 a
inner join master.dbo.spt_values b
on b.type='P' and b.number between 1 and len(a.TOption)