所以这里的代码不起作用:
SET QUOTED_IDENTIFIER ON
DECLARE
@tab char(1) = CHAR(9),
@arg VARCHAR(MAX) = 'N2'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Company Profile',
@recipients = 'randomemail.gmail.com',
@query = 'SET NOCOUNT ON
SELECT
e.EmplName,
FORMAT(SUM(t.ManHrs), @arg) AS [Hrs Logged to Jobs]
FROM EmplCode e JOIN TimeTicketDet t ON e.EmplCode = t.EmplCode
WHERE CAST(t.TicketDate AS DATE) = CAST(GETDATE() AS DATE)
AND t.WorkCntr <> 50
GROUP BY e.EmplName, t.WorkCntr
HAVING SUM(t.ManHrs) < 6
ORDER BY SUM(t.ManHrs)',
@subject = 'Hello',
@query_result_separator = @tab,
@execute_query_database = 'Company DB';
运行时出现以下错误:
无法初始化sqlcmd库,错误号为-2147467259 ..如果我删除了@query中的@arg变量而是使用
CAST(SUM(t.ManHrs) AS FLOAT)
它工作正常,即使离开声明的变量,所以我想我可以这样做,但我只是想知道错误信息甚至意味着什么。每当我在@query参数中引用时,我都必须使用变量吗?那是怎么回事?我怎么能在将来防止这种情况发生?感谢
答案 0 :(得分:1)
- 在外面构建您的查询,然后按以下方式发送邮件
SET QUOTED_IDENTIFIER ON
CREATE TABLE Table1 (id int, EmplName varchar(10), ManHrs int)
insert into table1 values (1, 'xxxxx', 8)
insert into table1 values (2, 'xxxxx', 4)
insert into table1 values (3, 'xxxxx', 6)
insert into table1 values (4, 'YYYYY', 8)
insert into table1 values (5, 'YYYYY', 4)
insert into table1 values (6, 'YYYYY', 6)
DECLARE
@tab char(1) = CHAR(9)
,@arg VARCHAR(MAX) = 'N2'
,@SQLquery NVARCHAR(1000)
SET @SQLquery = 'SET NOCOUNT ON
SELECT
e.EmplName,
FORMAT(SUM(e.ManHrs),''' + @arg + ''') AS [Hrs Logged to Jobs]
FROM table1 e
GROUP BY e.EmplName
HAVING SUM(e.ManHrs) > 6
ORDER BY SUM(e.ManHrs)'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Profile Name',
@recipients = 'randomemail.gmail.com',
@query = @SQLquery,
@subject = 'Hello',
@query_result_separator = @tab,
@execute_query_database = 'DB Name';
答案 1 :(得分:0)
[@ query =]&#39;查询&#39;
是要执行的查询。查询结果 可以作为文件附加,也可以包含在电子邮件正文中 信息。查询的类型为nvarchar(max),可以包含任何有效的查询 Transact-SQL语句。 请注意,查询是在单独执行的 session,所以调用sp_send_dbmail的脚本中的局部变量是 不适用于查询。
FORMAT(SUM(t.ManHrs), @arg) -- @arg variable is a problem
所以你的选择是硬编码值或连接查询字符串。