MSSQL2016
我需要从游标中过滤掉那些不返回结果的选项,以便不发送空的电子邮件。由于内部选择结果是html格式和强制转换,检查
IF @@ ROWCOUNT> 0
总是如此。更好的说,它始终是
@@ ROWCOUNT = 1
选择实际返回的行。
是否可以将实际的选择行数(在转换之前)作为临时参数传递给后续的EXEC sp_send_mail是/否检查?
OPEN C1;
FETCH NEXT FROM C1 INTO
@WishListID, @userEmail, @category, @range, @geoid, @searchCity, @userName, @GeoLocation
WHILE @@FETCH_STATUS = 0
BEGIN
SET @tableHTML =
N'<H4>Hello ' + @userName + '<H4>Here''s your Daily Digest</H4>' +
N'<table border="0">' +
N'<tr><th>Department</th>' +
N'<th>Name</th><th>Description</th>' +
N'<th>Place</th></tr>' +
CAST ( ( SELECT td = c.Name, '',
td = p.Name, '',
td = p.Description, '',
td = @searchCity
FROM Products as p
JOIN Categories AS c ON p.CategoryID = c.ID
JOIN AspNetUsers AS u ON p.UserID = u.Id
JOIN GeoData_ALL AS g ON u.GeoID = g.ID
WHERE p.IsApproved = 1 AND p.IsDeleted = 0 AND p.DateExpire > convert(date, getdate())
AND (@geoid = 0 or g.GeoLocation.STDistance(@GeoLocation) <= (@range*5000))
AND (@category = 0 or p.CategoryID = @category)
ORDER BY p.ID
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX) ) +
N'</table>' ;
IF @@ROWCOUNT > 0
EXEC sp_send_mail
@from='news@xyz.com',
@to = @userEmail,
@subject = 'Weekly xyz Digest',
@body = @tableHTML,
@bodytype = 'htmlbody',
@output_mesg = @out_mesg output,
@output_desc = @out_desc output ;
FETCH NEXT FROM C1 INTO
@WishListID, @userEmail, @category, @range, @geoid, @searchCity, @userName, @GeoLocation
END
CLOSE C1;
DEALLOCATE C1;
答案 0 :(得分:0)
当然可以,在游标循环中执行任何其他操作之前,您可以简单地使用SELECT COUNT(*)查询。
然而,执行您尝试执行的操作的一种更简洁的方法是检查@searchCity
的值是否存在@tableHTML
,而不是检查{{1 }}
要回答我认为你想要问的问题,那就是“如果我有一个@@ROWCOUNT>0
语句,我可以在后面找到SELECT中有多少行吗?”
答案是否正确。好吧,不是没有解析和分析你添加SELECT结果的变量的值。您可以随时计算您填充的字符串中SET @var='some text' + SELECT SomeStuff
的数量。
答案 1 :(得分:0)
你可以做到
select 1
填充@rowcount