我有表tb1(col1,col2),col2是varchar(50)。例如,
col1 col2
item1 abc
item2 a
item3 ed
我想编写一个存储过程来解析col2并创建一个临时表,如下所示:
col1 col2
item1 a
item1 b
item1 c
item2 a
item3 e
item3 d
有人可以帮助我吗?
答案 0 :(得分:2)
如果你知道字符串的最大长度,最简单的方法就是做一个简单的联合:
select col1, substring(col2, 1, 1) as col2
from t
where len(col2) >= 1 union all
select col1, substring(col2, 2, 1) as col2
from t
where len(col2) >= 2 union all
select col1, substring(col2, 3, 1) as col2
from t
where len(col2) >= 3 union all
如果长度永远不会太长,您可以这样做以简化查询:
select col1, substring(col2, nums.seqnum) as col2
from t cross join
(select row_number() over (order by (select NULL)) as seqnum
from Infromation_Schema.columns
) nums
where len(col2) <= nums.seqnum
或者,您可以在T-SQL中的while循环中执行此操作。
答案 1 :(得分:1)
试试这个:
您可以使用单个查询获取
SELECT COL1,SUBSTRING(COL2,NUMBER+1,1) AS COL2
FROM YOURTABLE T
JOIN MASTER..SPT_VALUES M
ON LEN(COL2)>NUMBER
WHERE M.TYPE='P'