存储过程中的SQL游标,用于填充字符串变量

时间:2011-01-07 20:09:22

标签: sql stored-procedures cursors

我有一个存储过程,其中包含一个循环遍历SQL记录的游标,并填充我稍后将用作电子邮件文本的字符串。我正在尝试将其打印出来以便在我继续之前进行验证,但它似乎没有填充字符串。这是我在SQL Server 2005中的存储过程。

CREATE PROCEDURE [dbo].[spBody] 
AS
DECLARE @MyCursor CURSOR
DECLARE @emailBody nvarchar(max)
DECLARE @statusName nvarchar(max)
DECLARE @deptCode nvarchar(max)
DECLARE @instructors nvarchar(max)
DECLARE @meetingTime nvarchar(max)

SET @MyCursor = CURSOR FAST_FORWARD For
Select StatusName, DeptCode, Instructors, Description from MyTable where StatusID = (select CAST(value AS INT) from Table2 where ConfigOption = 'RequiredStatus')

Open @MyCursor
FETCH NEXT FROM @MyCursor INTO @statusName, @deptCode, @instructors, @meetingTime


WHILE @@FETCH_STATUS = 0

BEGIN
 SET @emailBody = @emailBody + @statusName + ' ' + @deptCode + ' ' + @instructors + ' ' + @meetingTime 
 FETCH NEXT FROM @MyCursor INTO @statusName, @deptCode, @instructors, @meetingTime

END
CLOSE @MyCursor
Print @emailBody

DEALLOCATE @MyCursor 

2 个答案:

答案 0 :(得分:6)

这是因为@emailBody以NULL开头,并且任何与NULL的串联默认情况下都会产生NULL。做一个

SET @emailBody = '';

在脚本的开头。

另外,强烈考虑在存储过程的顶部添加SET NOCOUNT ON;语句 - 没有NOCOUNT ON会大大减慢proc的执行速度。

答案 1 :(得分:0)

为什么这个字符串连接需要一个游标。不要使用以下查询后缀

DECLARE @emailBody nvarchar(max) 

Set @emailBody = ''

Select @emailBody = @emailBody + StatusName + ' ' + DeptCode + ' ' + Instructors + ' ' + [Description] from MyTable where StatusID = (select CAST(value AS INT) from Table2 where ConfigOption = 'RequiredStatus')

Print @emailBody