如何将半冒号分隔值转换为列

时间:2013-03-06 04:23:15

标签: sql sql-server sql-server-2008

我正在开发一个集成项目,我收到三个字符串参数 项目代码 项目名称 量

并且值将采用此格式

ItemCod参数值 T1; T2; T3;

ItemName参数值 铅笔盒;橡皮擦;鼠标垫;

金额参数值 1900; 2000; 8900;

现在我想有一个程序,我将收到这些参数,查询将把它转换为列和记录。我不是SQLServer的人,我在Oracle中做了类似的事情发送。但是这个是以半冒号分隔接收并转换成列和行。我为质量差的帖子道歉。这是Oracle的尝试。

create or replace
PROCEDURE PROC_SENDREQDETAILS 
(
  P_REQ_NUMBER VARCHAR2  
, P_ATTRIBUTE1 VARCHAR2
, P_LOCATION_NAME VARCHAR2
, P_ITEM_ID VARCHAR2  
, P_QTY VARCHAR2
, P_NEED_BY_DATE VARCHAR2
, P_ATTRIBUTE3 VARCHAR2
) IS
BEGIN

INSERT INTO PO_REQUISITIONS_STAGING(req_number_segment1, attribute1, location_name, item_id, quantity, need_by_date, attribute3)
 select  regexp_substr(request_number,'[^;]+',1,level),
         regexp_substr(attribute1,'[^;]+',1,level),
         regexp_substr(location_name,'[^;]+',1,level),
         regexp_substr(item_id,'[^;]+',1,level),
         regexp_substr(quantity,'[^;]+',1,level),
         regexp_substr(need_by_date,'[^;]+',1,level),
         regexp_substr(attribute3,'[^;]+',1,level)
  from  (
      select P_REQ_NUMBER request_number, P_ATTRIBUTE1 attribute1, P_LOCATION_NAME location_name, P_ITEM_ID item_id, P_QTY quantity, P_NEED_BY_DATE need_by_date, P_ATTRIBUTE3 attribute3
      from dual
      )
  connect by regexp_substr(request_number,'[^;]+',1,level) is not null;
end;
--END PROC_SENDREQDETAILS;

1 个答案:

答案 0 :(得分:0)

可能与此相关:Can I tokenize a string using t-SQL

您可以使用XML查询来标记值:

INSERT INTO t
(cod, name)
VALUES
('T1;T2;',
 'Pencil Box;Eraser;');

---------------------------
|COD   |NAME              |
|T1;T2;|Pencil Box;Eraser;|
---------------------------

INSERT t2
SELECT
  CAST('<r>'+REPLACE(cod,';','</r><r>')+'</r>' AS XML).query('/r[1]').value('.','varchar(256)') cod,
  CAST('<r>'+REPLACE(name,';','</r><r>')+'</r>' AS XML).query('/r[1]').value('.','varchar(256)') name
FROM t;

INSERT t2
SELECT
  CAST('<r>'+REPLACE(cod,';','</r><r>')+'</r>' AS XML).query('/r[2]').value('.','varchar(256)') cod,
  CAST('<r>'+REPLACE(name,';','</r><r>')+'</r>' AS XML).query('/r[2]').value('.','varchar(256)') name
FROM t;

----------------
|COD|NAME      |
|T1 |Pencil Box|
|T2 |Eraser    |
----------------

http://sqlfiddle.com/#!3/258a5/1