时间:2021-07-01 10:21:17 帮助过:3人阅读
Sqlserver 字符串变为一个表 可以根据需求自行更改,灵活运用 无 declare @LSTR_InsertHead varchar(500)--列名declare @LSTR_InsertFields varchar(max)--数据字符串declare @splitrol varchar(2)--行分割符declare @splitcol varchar(2)--列分隔符set @spli
Sql serverdeclare @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)