删除 sp_send_dbmail 中的多余空格

Remove extra spaces in sp_send_dbmail

我有以下 table:

CREATE TABLE [dbo].[MyTable](
    [Day_ID] [nvarchar](50) NULL,
    [SAS] [nvarchar](50) NULL,
    [STAMP] [datetime] NULL DEFAULT (getdate())
)

其中包含以下数据:

我还有一个 SP,它从 MyTable 读取所有数据并将其作为电子邮件正文发送。

SET NOCOUNT ON;

    EXEC msdb.dbo.sp_send_dbmail 
        @profile_name = 'MyMailProfile'
        ,@recipients = 'me@account.com'
        ,@subject = 'This is the object'
        ,@body = 'This is the body:'
        ,@body_format = 'TEXT'
        ,@query = 'SET NOCOUNT ON select [Day_ID],[SAS] from MyTable SET NOCOUNT OFF'
        ,@attach_query_result_as_file = 0
        ,@query_result_separator = '|'
        ,@exclude_query_output = 1
        ,@query_result_no_padding = 0
        ,@query_result_header = 0
        ,@append_query_error=1

一切正常,但我的问题是在正文中结果如下所示:

2017_12_06_01                                   |Red                                                  
2017_12_06_02                                   |Yellow                                               
2017_12_06_03                                   |Green                                                
2017_12_06_04                                   |Blue                                                 

换句话说,SQL 服务器知道这些列可能有 50 个字符长,所以它们用 space 填充不包含字符的 space。如果您认为将数值写入列(例如 NUMERIC)时也会发生这种情况,这将非常无聊。 我试过 LTRIM 和 RTRIM 但没有任何改变。

我正在使用 SQL Server 2005。

您需要 运行 两个查询 - 第一个是计算实际长度,第二个是检索电子邮件的数据。显然,这可能会有很高的成本。

类似于:

declare @maxDay int
declare @maxSAS int

select @maxDay = MAX(LEN(RTRIM(Day_ID))),@maxSAS = MAX(LEN(RTRIM(SAS))) from MyTable

declare @sql varchar(max)
set @sql = 'SET NOCOUNT ON select CONVERT(nvarchar(' + CONVERT(varchar(10),@maxDay) +
           '),[Day_ID]) as Day_ID,CONVERT(nvarchar(' + CONVERT(varchar(10),@maxSAS) +
           '),[SAS]) as SAS from MyTable SET NOCOUNT OFF'

然后在你的sp_send_dbmail调用中使用@sql

I've tried with LTRIM and RTRIM but nothing changed.

不会。结果集中的每一列都有一个固定的类型。输入到您的例如RTRIM() 来电是 nvarchar(50)。在不知道所有行的内容的情况下,SQL 服务器可以使用表达式从 RTRIM() 的输出中导出什么可能的数据类型?它仍然只能是 nvarchar(50),所以这仍然是结果集中列的类型。对于现在的所有服务器,可能有一行包含 50 个非空白字符,结果仍然需要显示。

参数 @query_result_no_padding 应该允许您这样做。

更改自:

@query_result_no_padding = 0

@query_result_no_padding = 1

[ @query_result_no_padding ] @query_result_no_padding The type is bit. The default is 0. When you set to 1, the query results are not padded, possibly reducing the file size.If you set @query_result_no_padding to 1 and you set the @query_result_width parameter, the @query_result_no_padding parameter overwrites the @query_result_width parameter. + In this case no error occurs. If you set the @query_result_no_padding to 1 and you set the @query_no_truncate parameter, an error is raised.

来源:https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-send-dbmail-transact-sql