-
Notifications
You must be signed in to change notification settings - Fork 682
/
Copy pathdbo.sp_PrintString.sql
70 lines (61 loc) · 1.87 KB
/
dbo.sp_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
IF OBJECT_ID('dbo.sp_PrintString', 'P') IS NULL
EXEC ('CREATE PROCEDURE dbo.sp_PrintString AS SELECT 1');
GO
ALTER PROCEDURE dbo.sp_PrintString (
@str NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @line NVARCHAR(MAX),
@startLocation INT = 1,
@length INT = 0,
@totalLength INT = DATALENGTH(@str),
@current INT = 1;
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
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