*Edited thanks to Mark's insight*
Figured I'd post this sql stored procedure that's been giving me a migraine for the last 5-6 hours.
Basically I'm querying a webservice that returns a big message, and I wanted to store it in another company's POS system to print out on the receipt at the counter. Problem is the receipt is only 44 characters wide and they store receipt messages in a TransactionID, LineNumber, Message format in the table so I had to parse it myself while being sure not to break up any words.
It's pretty easy to modify it to specify any number of characters per line. Here's the result:
CREATE PROCEDURE dbo.ParseReceiptMessage(
@TransactionID int,
@Message nvarchar(4000)
)
AS
DECLARE
@CursorPos int,
@LastSpacePos int,
@TextLength int,
@PrintOrder int,
@LineMessage nvarchar(44)
SET @TextLength = len(@Message)
SET @PrintOrder = 1
SET @CursorPos = 0
SET @LastSpacePos = 1
WHILE ( @CursorPos < @TextLength)
BEGIN
SET @CursorPos = @CursorPos + 44
SET @LineMessage = SUBSTRING(@Message, @CursorPos - 43, @CursorPos)
SET @LastSpacePos = (@CursorPos - (PATINDEX('% %', REVERSE(@LineMessage))-1)) - (@CursorPos - 44)
SET @LineMessage = SUBSTRING(@Message, @CursorPos - 43, @LastSpacePos)
INSERT INTO SomeTable
(TransactionID, PrintOrder, Message)
VALUES
(@TransactionID, @PrintOrder, @LineMessage)
SET @CursorPos = @CursorPos - (44 - @LastSpacePos)
SET @PrintOrder = @PrintOrder + 1
END
Go