我有一个varchar列,它由CRLF分隔的各种文本组成。我需要拆分此列,每个部分都运行到下一个CRLF。然后需要将这些子字符串作为新行插入到新表(我已经创建)中。具有varchar列的表是tblJobsTest,该列称为Notes。新表是tblJobAppointmentNotes,由JobID和AppointmentNote组成。
这是我到目前为止所拥有的......
DECLARE @crlf CHAR(2) = CHAR(13) + CHAR (10)
DECLARE @Note VARCHAR(MAX) = null
WHILE (SELECT LEN(Notes) FROM tblJobsTest) > 0
BEGIN
IF CHARINDEX(@crlf,Notes) > 0
BEGIN
SET @Note = SUBSTRING(Notes, 0, CHARINDEX(@crlf,Notes))
INSERT INTO tblJobAppointmentNotes (AppointmentNote)
VALUES (@Note)
Update tblJAN
SET tblJAN.JobID = tblJT.JobID
From tblJobAppointmentNotes tblJAN
INNER JOIN tblJobsTest tblJT ON tblJAN.JobID = tblJT.JobID
UPDATE tblJobsTest
SET Notes= SUBSTRING(Notes, LEN(@Note) + 1, LEN(Notes))
END
ELSE
INSERT INTO tblJobAppointmentNotes (JobID, AppointmentNote)
SELECT JobID, Notes FROM tblJobsTest
END
我遇到的问题是列'名称'注释'未标识。 CHARINDEX无法查找我猜的列,所以我认为我需要使用某种形式的CTE,所以这段代码可以引用tblJobsTest中的每一行?
有人有什么想法吗?感谢
答案 0 :(得分:0)
在这里......将其粘贴到一个空的查询窗口并执行。适应您的需求......
编辑:同样的过程,但基于集合的方法一次完成这一整个表...DECLARE @TableWithLongText TABLE(ID INT, LongText VARCHAR(MAX));
DECLARE @TableToInsertParts TABLE(ID INT IDENTITY, TWLT_ID INT,PartNr INT, eachLine VARCHAR(MAX));
INSERT INTO @TableWithLongText VALUES
(1,'This' + CHAR(13) + CHAR(10) + 'is the text for ID=1' + CHAR(13) + CHAR(10) + 'with' + CHAR(13) + CHAR(10) + '4 lines')
,(2,'This' + CHAR(13) + CHAR(10) + 'is the text for ID=2' + CHAR(13) + CHAR(10) + 'with 3 lines');
WITH Recoded(ID,x) AS
(
SELECT ID
,CAST('<root><r>' + REPLACE(twlt.LongText,CHAR(13)+CHAR(10),'</r><r>') + '</r></root>' AS XML)
FROM @TableWithLongText AS twlt
)
INSERT INTO @TableToInsertParts(TWLT_ID,PartNr,eachLine)
SELECT ID
,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID)
,a.b.value('.','varchar(max)')
FROM Recoded
CROSS APPLY Recoded.x.nodes('/root/r') a(b);
SELECT * FROM @TableToInsertParts;