我之前使用的是SQL Server 2014。当我尝试执行以下查询
时EXECUTE msdb.dbo.sp_send_dbmail
@profile_name = "Mail"
,@recipients = "rkont@xxx.gr"
,@from_address = "xxx.eye@gmail.com"
,@execute_query_database = "EYE"
,@query = "SELECT TOP (100) DateTime, VariableID, VariableName,
VariableValue_NumValue as VariableValue, VariableLabel as VariableLabel, SiteID, SiteName,
DeviceName from dbo.v_AggregatedReport where ClientID = 1 and SiteID in
(select SiteID from dbo.v_AccessList where UserID = 16) and DateTime is not null and
VariableValue_NumValue is not null and DateTime
between Web Aug 16 2017 00:00:00 GMT+0300 (GTB Daylight Time) and
Sat Sep 16 2017 23:59:59 GMT+0300 (GTB Daylight Time) AND SiteID in (39) and
VariableName in (\'Total Active Energy\')"
,@subject = "Aggregated-Reports eye.v2"
,@body= "Aggregated Reports about a month"
,@attach_query_result_as_file = 1
,@query_attachment_filename = "Aggregated-Reports.csv"
,@query_result_separator = " "
,@query_result_no_padding= 1
,@exclude_query_output =1
,@append_query_error = 0
,@query_result_header =1;
但是我收到了这个错误:
标有以' SELECT TOP(100)DateTime,VariableID,VariableName,VariableValue_NumValue作为VariableValue,VariableLabel作为VariableLab'太长。最大长度为128
我搜索了很多,但找不到解决方案。
答案 0 :(得分:2)
正如HoneyBadger所说,你使用双引号,你应该使用单引号。您还错误地转发了@query
中的单引号,没有限定DateTime
列名称,因为它是SQL关键字,也没有正确指定日期。
我没有更改SiteID
列周围的重叠条件,因为我不知道您是否需要将其与子查询中的结果匹配,或者只是等于39
?
您似乎来自另一种开发语言,并且正在尝试将相同的原则应用于您的SQL代码。我建议做一些关于SQL语法和最佳实践的研究:
EXECUTE msdb.dbo.sp_send_dbmail
@profile_name = 'Mail'
,@recipients = 'rkont@xxx.gr'
,@from_address = 'xxx.eye@gmail.com'
,@execute_query_database = 'EYE'
,@query = 'select top (100) [DateTime]
,VariableID
,VariableName
,VariableValue_NumValue as VariableValue
,VariableLabel as VariableLabel
,SiteID
,SiteName
,DeviceName
from dbo.v_AggregatedReport
where ClientID = 1
and SiteID in (select SiteID
from dbo.v_AccessList
where UserID = 16
)
and SiteID in (39) -- This criteria clashes with the sub-select above.
and VariableValue_NumValue is not null
and [DateTime] >= ''20170816''
and [DateTime] < ''20170917'' -- Always look for less that the start of the next period. Time is infinite yet current data types are not.
and VariableName in (''Total Active Energy'')
'
,@subject = 'Aggregated-Reports eye.v2'
,@body= 'Aggregated Reports about a month'
,@attach_query_result_as_file = 1
,@query_attachment_filename = 'Aggregated-Reports.csv'
,@query_result_separator = ' '
,@query_result_no_padding= 1
,@exclude_query_output =1
,@append_query_error = 0
,@query_result_header =1;