sql把字符数组转换成表
需求:把字符串1,2,3变成表里的行数据
方法:用自定义函数实现
/* 获取字符串数组的 Table */ if exists (select 1 from sysobjects where id = object_id('Get_StrArrayStrOfTable' )) drop Function Get_StrArrayStrOfTable go CREATE function Get_StrArrayStrOfTable( @SourceSql varchar (max), @StrSeprate varchar (10) ) returns @temp table( F1 varchar (100)) as begin declare @i int set @SourceSql =rtrim( ltrim(@SourceSql )) set @i =charindex( @StrSeprate,@SourceSql ) while @i >=1 begin insert @temp values(left( @SourceSql,@i -1)) set @SourceSql =substring( @SourceSql,@i +1, len(@SourceSql )-@i) set @i =charindex( @StrSeprate,@SourceSql ) end if @SourceSql <>'' insert @temp values( @SourceSql) return end GO
用法:
SELECT * from dbo.Get_StrArrayStrOfTable('1,2,3',',')