使用分隔字符串:
create function f_splitstrX(@SourceSql varchar(8000),@StrSeprate varchar(100))
returns @temp table(F1 varchar(100))
as
begin
declare @ch as varchar(100)
set @SourceSql=@SourceSql+@StrSeprate
while(@SourceSql<>'')
begin
set @ch=left(@SourceSql,charindex(@StrSeprate,@SourceSql,1)-1)
insert @temp values(@ch)
set @SourceSql=stuff(@SourceSql,1,charindex(@StrSeprate,@SourceSql,1),'')
end
return
end
--使用时
declare @ans varchar(200)
select @ans=ans from 表 where 题目ID=5
declare @columns varchar(1000)
set @columns =''
select @columns=@columns+','+F1 from dbo.f_splitstrX('、',@ans)
set @columns=stuff(@columns,1,1,'')
exec ('select ' +@
+ ' from 表 where 题目ID=5')