J.D*_*.D. 2 sql-server ssms sql-server-2016
每当我编写动态 SQL 时,我通常会PRINT @DynamicSQL在该语句正上方的注释中包含一条语句EXEC sp_ExecuteSQL @DynamicSQL,以便在需要时可以轻松读取和调试动态 SQL。
我意识到 PRINT 语句在截断字符串之前有 8,000 个字符的限制。我知道我可以循环遍历我的 @DynamicSQL 变量,将 8,000 划分为它的长度,并每次迭代打印每个 8,000 块,但是随后您会丢失 @DynamicSQL 中的语句跨两个块的格式,这违背了我的目的。
有没有人找到更好的方法来在打印超过 8,000 个字符的字符串时保留格式?...也许通过自定义函数或过程?
我个人没有使用过这种技术,但你可以尝试LongPrint。从那篇文章:
这个非常简单的过程旨在克服 SQL 打印命令中的限制,该命令会截断长度超过 8000 个字符的字符串。
它将以小于 8000 个字符的子字符串形式打印传递给它的文本。如果文本中有回车符 (CR),它将在回车符处分解子字符串,并且打印版本将准确反映传递的字符串。
如果文本中的 CR 不足,它将以 8000 个字符的块形式打印出来,并在该处添加一个额外的回车符。
如果传递一个空值,它实际上什么也不做。
我在尝试调试生成非常长的动态 SQL 部分的脚本时需要显示非常长的字符串。当我没有立即在 SQLServerCentral.com 上找到执行此操作的脚本时,我决定自己编写一个脚本比搜索更广泛的互联网更快。
复制该帖子中的代码:
CREATE PROCEDURE [dbo].[LongPrint]
@String NVARCHAR(MAX)
AS
/*
Example:
exec LongPrint @string =
'This String
Exists to test
the system.'
*/
/* This procedure is designed to overcome the limitation
in the SQL print command that causes it to truncate strings
longer than 8000 characters (4000 for nvarchar).
It will print the text passed to it in substrings smaller than 4000
characters. If there are carriage returns (CRs) or new lines (NLs in the text),
it will break up the substrings at the carriage returns and the
printed version will exactly reflect the string passed.
If there are insufficient line breaks in the text, it will
print it out in blocks of 4000 characters with an extra carriage
return at that point.
If it is passed a null value, it will do virtually nothing.
NOTE: This is substantially slower than a simple print, so should only be used
when actually needed.
*/
DECLARE
@CurrentEnd BIGINT, /* track the length of the next substring */
@offset tinyint /*tracks the amount of offset needed */
set @string = replace( replace(@string, char(13) + char(10), char(10)) , char(13), char(10))
WHILE LEN(@String) > 1
BEGIN
IF CHARINDEX(CHAR(10), @String) between 1 AND 4000
BEGIN
SET @CurrentEnd = CHARINDEX(char(10), @String) -1
set @offset = 2
END
ELSE
BEGIN
SET @CurrentEnd = 4000
set @offset = 1
END
PRINT SUBSTRING(@String, 1, @CurrentEnd)
set @string = SUBSTRING(@String, @CurrentEnd+@offset, 1073741822)
END /*End While loop*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3129 次 |
| 最近记录: |