字符串变表带有表头

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

declare @LSTR_InsertHead varchar(500)--列名
declare @LSTR_InsertFields varchar(max)--数据字符串
declare @splitrol varchar(2)--行分割符
declare @splitcol varchar(2)--列分隔符
set @splitrol='⒉'
set @splitcol='⒈'
set  @LSTR_InsertHead='product⒈unitid⒈levelid⒈cost'--表头参数
set @LSTR_InsertFields='001888⒈8⒈9⒈¥⒉000507⒈⒈⒈¥⒉001339⒈⒈⒈¥⒉001340⒈⒈⒈¥⒉001335⒈⒈⒈¥'--数据参数

set @LSTR_InsertHead=@LSTR_InsertHead+@splitcol
declare @HeadStr varchar(20)--列名
declare @HeadSql varchar(200)--列头生成
set @HeadSql='select '
while CHARINDEX('⒈',@LSTR_InsertHead)<>0
begin
	SET @HeadStr = substring(@LSTR_InsertHead,1,charindex(@splitcol,@LSTR_InsertHead)-1)--截取表头
	if	@HeadSql='select '
		set  @HeadSql=@HeadSql+''''' as '+@HeadStr
	else
		set  @HeadSql=@HeadSql+','''' as '+@HeadStr
	SET @LSTR_InsertHead = stuff(@LSTR_InsertHead,1,charindex(@splitcol,@LSTR_InsertHead),'') --去掉已截取内容
end
/*
以下为生成表
*/
set  @HeadSql=@HeadSql+' where 1=2 union '
set @LSTR_InsertFields=REPLACE(@LSTR_InsertFields,@splitrol,''' union select ''')

set @LSTR_InsertFields=@HeadSql+'select  '''+REPLACE(@LSTR_InsertFields,@splitcol,''',''')+''''

print(@LSTR_InsertFields)
exec(@LSTR_InsertFields)