我有一个要拆分的字符串;它的格式如下:
---------------------------------------------------------
HEADING DETAILS HERE:
~
INVOICE1^VALUE1^VALUE2^
INVOICE2^VALUE1^VALUE2^
INVOICE3^VALUE1^VALUE2^
TOTAL^OFVALUE1^OFVALUE2^
~
FOOTER DETAILS HERE
---------------------------------------------------------
我的输出应该是一个包含 3 列的表格:
| INVOICE | VALUE1 | VALUE2 |
INVOICE 1---------- VALUE1 ---------- VALUE2
INVOICE 2---------- VALUE1 ---------- VALUE2
INVOICE 3---------- VALUE1 ---------- VALUE2
我的想法是用第一个分隔符分割 ~ 并用分隔符分割 2 ^
我做了一个分割函数,这是我第一次用分隔符分割的结果~
ROW 1 HEADER DETAILS HERE:
ROW 2 INVOICE1^VALUE1^VALUE2^ INVOICE2^VALUE1^VALUE2^ INVOICE3^VALUE1^VALUE2^
ROW 3 FOOTER DETAILS HERE
但是,我需要做的是将结果放入列而不是行。另外,我需要获得第 2 行的结果并再次拆分并将其放在这样的列中:
INVOICE column - VALUE1 column - VALUE2 column
INVOICE 1---------- VALUE1 ---------- VALUE2
INVOICE 2---------- VALUE1 ---------- VALUE2
INVOICE 3---------- VALUE1 ---------- VALUE2
我希望有人能够阅读这个问题并帮助我编写我的 TSQL。
跟进问题:2013 年 8 月 13 日
我试图将 Rs 的代码更改为这样的东西......
USE [test]
GO
/****** Object: StoredProcedure [dbo].[SplitSP4] Script Date: 8/13/2013 7:33:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[SplitSP4]
-- Add the parameters for the stored procedure here
--<@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,
--<@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
@TABLE_id varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
--SET NOCOUNT ON;
declare @string varchar(8000)
declare @stringXML xml
declare @NewLine char(2)
set @NewLine=char(13)+char(10)
set @string = (SELECT [dbo].[TABLE_NAME].[iam_string] FROM [dbo].[TABLE_NAME] WHERE [dbo].[TABLE_NAME].[id] = @TABLE_id)
--'HEADING DETAILS HERE:
--~
--INVOICE1^VALUE1^VALUE2^
--INVOICE2^VALUE1^VALUE2^
--INVOICE3^VALUE1^VALUE2^
--TOTAL^OFVALUE1^OFVALUE2^
--~
--FOOTER DETAILS HERE'
declare @table1 table(cols varchar(max))
--convert string to xml
SELECT @stringXML = CONVERT(xml,'<root><i>' +
Replace(@string, @NewLine, '</i><i>') + '</i></root>')
--split xml string into different rows
insert into @table1
select Cols = I.c.value('.', 'varchar(MAX)')
from @stringXML.nodes('/root/i') I(c)
--split invoice rows into columns
select
Inv.value('/Invoice[1]/Attribute[1]','varchar(50)') AS [Invoice],
Inv.value('/Invoice[1]/Attribute[2]','varchar(50)') AS [Value1],
Inv.value('/Invoice[1]/Attribute[3]','varchar(50)') AS [Value2]
from
(
select CONVERT(XML,'<Invoice><Attribute>'
+ REPLACE([cols],'~', '</Attribute><Attribute>')
+ '</Attribute></Invoice>') Inv
from @table1 where cols like '%^%'
) x
end
...让我能够为 CRYSTAL 报告制作一个存储程序。但似乎当我执行这个 STORED PROCEDURE 时它返回了这个错误。
消息 9421,级别 16,状态 1,过程 SplitSP4,第 34
行 XML 解析:第 1 行,字符 31,非法名称字符
我想知道如何修复我的代码以适应示例 XML 代码?