forked from ktaranov/sqlserver-kit
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathusp_PrintString.sql
90 lines (78 loc) · 2.28 KB
/
usp_PrintString.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
IF OBJECT_ID('dbo.usp_PrintString', 'P') IS NULL
EXECUTE ('CREATE PROCEDURE dbo.usp_PrintString AS SELECT 1');
GO
ALTER PROCEDURE dbo.usp_PrintString (
@str NVARCHAR(MAX)
)
AS
/*
EXEC dbo.usp_PrintString REPLICATE(¸, 5000);
*/
BEGIN
DECLARE @line NVARCHAR(MAX)
, @StartLocation INT
, @Length INT
, @TotalLength INT
, @Current INT
SELECT @StartLocation = 1
,@TotalLength = DATALENGTH(@str)
,@Current = 1
,@Length = 0
DECLARE @PrintLine NVARCHAR(MAX) =
N'DECLARE @pos int = 1
WHILE @pos <= LEN(@line)
BEGIN
PRINT SUBSTRING(@line, @pos, 4000);
SET @pos = @pos + 4000;
END;'
WHILE @Current <= @TotalLength
BEGIN
IF (
SUBSTRING(@str, @Current, 2) IN (
CHAR(0x0D) + CHAR(0x0A)
,CHAR(0x0A) + CHAR(0x0D)
)
)
BEGIN
IF @Length <= 0
PRINT '';
ELSE
BEGIN -- line
SELECT @line = SUBSTRING(@str, @StartLocation, @Length);
EXEC sp_executesql @PrintLine
,N'@line NVARCHAR(max)'
,@line;
END
SELECT @StartLocation = @Current + 2
,@Current = @Current + 2
,@Length = 0;
CONTINUE;
END
ELSE IF (
SUBSTRING(@str, @Current, 1) IN (
CHAR(0x0D)
,CHAR(0x0A)
)
)
BEGIN
IF @Length <= 0
PRINT '';
ELSE
BEGIN
SELECT @line = SUBSTRING(@str, @StartLocation, @Length);
EXEC sp_executesql @PrintLine
,N'@line NVARCHAR(max)'
,@line;
END
SELECT @StartLocation = @Current + 1
,@Current = @Current + 1
,@Length = 0;
CONTINUE;
END
SELECT @Current = @Current + 1
, @Length = @Length + 1;
END
IF (@StartLocation <= DATALENGTH(@str))
PRINT SUBSTRING(@str, @StartLocation, DATALENGTH(@str))
END;
GO