简体   繁体   中英

SQL Cursor within Stored Procedure to populate string variable

I have a stored procedure that contains a cursor to loop through SQL records and populates the string which I will use later as my email text. I'm trying to print it out to verify before I can proceed with it but it seems to not populate the string. Here is my stored procedure in 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 

It's because @emailBody starts out as NULL, and any concatenation with NULL yields NULL by default. Do a

SET @emailBody = '';

at the beginning of your script.

Also, strongly consider adding a SET NOCOUNT ON; statement at the top of your stored procedure -- not having NOCOUNT ON can greatly slow the execution of your proc.

Why do you need a cursor for this string concat. Wont the following query suffix

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM