I have a procedure that has a nested cursor to return the rooms of the hotel, with a nested cursor inside that cursor to return the cost for that room over the different periods of time. However, when I run my procedure, I get the hotel id and name (as I should), the room name and description (as I should), but then the first cost value gets infinitely printed out.
CREATE PROCEDURE sp_GetRackRates
#HotelID smallint
AS
BEGIN
DECLARE #HotelName varchar(30)
DECLARE #RoomID smallint
DECLARE #RoomNumber smallint
DECLARE #RTDescription varchar(200)
DECLARE #RackRate smallmoney
DECLARE #RackRateBegin date
DECLARE #RackRateEnd date
SELECT #HotelName = HotelName
FROM Hotel
WHERE HotelID = #HotelID
PRINT 'Hotel ID: ' + CAST(#HotelID AS varchar(max)) + ' - ' + CAST(#HotelName as
varchar(max))
PRINT ' '
SELECT #RoomID = RoomID, #RoomNumber = RoomNumber, #RTDescription = RTDescription
FROM (Room
INNER JOIN RoomType ON Room.RoomTypeID = RoomType.RoomTypeID)
WHERE Room.HotelID = #HotelID
SELECT #RackRate = RackRate, #RackRateBegin = RackRateBegin, #RackRateEnd =
RackRateEnd
FROM (RackRate
INNER JOIN Room ON RackRate.HotelID = Room.HotelID)
WHERE RackRate.HotelID = #HotelID AND RoomNumber = #RoomNumber
DECLARE cr_GetRoom CURSOR
FOR
SELECT RoomID, RoomNumber, RTDescription
FROM (Room
INNER JOIN RoomType ON Room.RoomTypeID = RoomType.RoomTypeID)
WHERE Room.HotelID = #HotelID
DECLARE cr_GetRackRates CURSOR
FOR
SELECT RackRate, RackRateBegin, RackRateEnd
FROM (RackRate
INNER JOIN Room ON RackRate.HotelID = Room.HotelID)
WHERE RackRate.HotelID = #HotelID AND RoomNumber = #RoomNumber
OPEN cr_GetRoom
FETCH NEXT FROM cr_GetRoom
INTO #RoomID, #RoomNumber, #RTDescription
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'Room ' + CAST(#RoomNumber AS varchar(max)) + ': ' + CAST(#RTDescription
as varchar(max))
OPEN cr_GetRackRates
FETCH NEXT FROM cr_GetRackRates
INTO #RackRate, #RackRateBegin, #RackRateEnd
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'Rate: $' + CAST(#RackRate as varchar(max)) + ' valid ' +
cast(#RackRateBegin AS varchar(max)) + ' to ' + CAST(#RackRateEnd AS
varchar(max))
END
CLOSE cr_GetRackRates
PRINT ' '
END
CLOSE cr_GetRoom
DEALLOCATE cr_GetRackRates
DEALLOCATE cr_GetRoom
END
A Sample output looks as follows:
HotelID: 2100 - Sunridge B&B
Room 101: Single
Rate: $125.00 valid 2023-03-16 to 2023-11-14
Rate: $125.00 valid 2023-03-16 to 2023-11-14
Rate: $125.00 valid 2023-03-16 to 2023-11-14
Rate: $125.00 valid 2023-03-16 to 2023-11-14
Rate: $125.00 valid 2023-03-16 to 2023-11-14
Rate: $125.00 valid 2023-03-16 to 2023-11-14
Rate: $125.00 valid 2023-03-16 to 2023-11-14
Where the Rate: $125.00 continues infinitely, even though there is only one of those values in the database.
Why does the nested cursor keep repeating the same value? I've tried using SELECT DISTINCT but it kept giving the same results.
I figured out what my issue was.
In the blocks
FETCH NEXT FROM cr_GetRoom
INTO #RoomID, #RoomNumber, #RTDescription
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'Room ' + CAST(#RoomNumber AS varchar(max)) + ': ' + CAST(#RTDescription
as varchar(max))
OPEN cr_GetRackRates
FETCH NEXT FROM cr_GetRackRates
INTO #RackRate, #RackRateBegin, #RackRateEnd
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'Rate: $' + CAST(#RackRate as varchar(max)) + ' valid ' +
cast(#RackRateBegin AS varchar(max)) + ' to ' + CAST(#RackRateEnd AS
varchar(max))
END
CLOSE cr_GetRackRates
PRINT ' '
END
I was not fetching the next item, so it was just sitting at the same item constantly returning it.
It should be:
FETCH NEXT FROM cr_GetRoom
INTO #RoomID, #RoomNumber, #RTDescription
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'Room ' + CAST(#RoomNumber AS varchar(max)) + ': ' + CAST(#RTDescription
as varchar(max))
OPEN cr_GetRackRates
FETCH NEXT FROM cr_GetRackRates
INTO #RackRate, #RackRateBegin, #RackRateEnd
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'Rate: $' + CAST(#RackRate as varchar(max)) + ' valid ' +
cast(#RackRateBegin AS varchar(max)) + ' to ' + CAST(#RackRateEnd AS
varchar(max))
FETCH NEXT FROM cr_GetRackRates
INTO #RackRate, #RackRateBegin, #RackRateEnd
END
CLOSE cr_GetRackRates
PRINT ' '
FETCH NEXT FROM cr_GetRoom
INTO #RoomID, #RoomNumber, #RTDescription
END
You seem to mix cursors with regular variable fetching and not doing actual loops, and declaring the cursors in wrong position so i'm gonna assume your fixed code doesn't work, so please forgive me if my assumption is not correct.
The improved(?) version:
CREATE PROCEDURE spGetRackRates
#HotelID smallint
AS
BEGIN
DECLARE #HotelName varchar(30)
DECLARE #RoomID smallint
DECLARE #RoomNumber smallint
DECLARE #RTDescription varchar(200)
DECLARE #RackRate smallmoney
DECLARE #RackRateBegin date
DECLARE #RackRateEnd date
SELECT #HotelName = HotelName
FROM Hotel
WHERE HotelID = #HotelID
PRINT 'Hotel ID: ' + CAST(#HotelID AS varchar(max)) + ' - ' + CAST(#HotelName as
varchar(max))
PRINT ' '
DECLARE cr_GetRoom CURSOR READ_ONLY FORWARD_ONLY LOCAL STATIC FOR
SELECT RoomID, RoomNumber, RTDescription
FROM Room
INNER JOIN RoomType ON Room.RoomTypeID = RoomType.RoomTypeID
WHERE Room.HotelID = #HotelID
OPEN cr_GetRoom
WHILE 1 = 1
BEGIN
FETCH NEXT FROM cr_GetRoom
INTO #RoomID, #RoomNumber, #RTDescription
IF ##FETCH_STATUS <> 0
BREAK
DECLARE cr_GetRackRates CURSOR READ_ONLY FORWARD_ONLY LOCAL STATIC FOR
SELECT RackRate, RackRateBegin, RackRateEnd
FROM RackRate
INNER JOIN Room ON RackRate.HotelID = Room.HotelID
WHERE RackRate.HotelID = #HotelID AND RoomNumber = #RoomNumber
OPEN cr_GetRackRates
WHILE 1 = 1
BEGIN
FETCH NEXT FROM cr_GetRackRates
INTO #RackRate, #RackRateBegin, #RackRateEnd
IF ##FETCH_STATUS <> 0
BREAK
PRINT 'Room ' + CAST(#RoomNumber AS varchar(max)) + ': ' + CAST(#RTDescription as varchar(max))
PRINT 'Rate: $' + CAST(#RackRate as varchar(max)) + ' valid ' +
cast(#RackRateBegin AS varchar(max)) + ' to ' + CAST(#RackRateEnd AS
varchar(max))
END
PRINT ' '
CLOSE cr_GetRackRates
DEALLOCATE cr_GetRackRates
END
CLOSE cr_GetRoom
DEALLOCATE cr_GetRoom
END
A couple of points:
Unless you want to update data, you should declare your cursors as local static, which avoids pollution the namespace of cursors, and also improve your performance.
You have to declare the inner cursor "inside" the loop after your fetch the room number, otherwise it just becomes static bound to the original room variable.
I prefer to use WHERE 1 = 1 loops and check for fetch_status after the fetching of variables. This is because a lot of times one forgets to fetch the variables again in the end of the loop which messes things up.
Related
How can I get all columns (in the DB) having only NULL Value.?
If there are 2 tables:
T1
A B
1 NULL
2 NULL
NULL NULL
And T2
C D
NULL 920
NULL NULL
NULL 2323
I want to return B and C
Do you mean B and C?
Try:
Declare #schemaname varchar(255), #tablename varchar(255)
DECLARE table_cur cursor for
SELECT s.name,t.name
FROM sys.tables t Join sys.schemas s on t.schema_id=s.schema_id
OPEN table_cur
FETCH NEXT FROM table_cur into #schemaname, #tablename
WHILE ##FETCH_STATUS = 0
BEGIN
Declare #col varchar(255), #cmd varchar(max)
DECLARE column_cur cursor for
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #tablename
OPEN column_cur
FETCH NEXT FROM column_cur into #col
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #cmd = 'IF NOT EXISTS (SELECT top 1 * FROM ' + #schemaname + '.' + #tablename +' WHERE [' + #col + '] IS NOT NULL) BEGIN print '' Table: ' + #tablename + ', Column: ' + #col + ''' end'
EXEC(#cmd)
FETCH NEXT FROM column_cur into #col
END
CLOSE column_cur
DEALLOCATE column_cur
FETCH NEXT FROM table_cur into #schemaname, #tablename
END
CLOSE table_cur
DEALLOCATE table_cur
I have created a script to compare the tables of two databases to find differences. I want to be able to manually set two variables (one for each database) and have the 'USE' statement use the variable value for one of the databases but it changes context and does work correctly.
This is what I am trying to use to populating a variable (#Use) with the USE code to execute
--set #Use = 'USE ' + #NewProdDB + ';SELECT name FROM sys.tables'
--EXEC (#Use)
This is the entire query:
--========================================================================================================
-- Used to find table values in the test upgrade system database not found the newly upgraded system
-- database. Make sure change the system database names before running the query.
-- Also, select the upgraded database to run against
--========================================================================================================
DECLARE #NewProdDB VARCHAR(100)
DECLARE #TestUpgradeDB VARCHAR(100)
DECLARE #Columns VARCHAR (MAX)
DECLARE #Query VARCHAR(MAX)
DECLARE #ResultsTest VARCHAR(MAX)
DECLARE #SetResultsCursor NVARCHAR(MAX)
DECLARE #Fetcher NVARCHAR(MAX)
DECLARE #Use NVARCHAR(50)
DECLARE #ListOfTables VARCHAR(100)
DECLARE #WTF NVARCHAR(max)
DECLARE #rescanCode nvarchar(max)
/* Enter Upgraded system DB here */
SET #NewProdDB = 'zSBSSYS'
/* Enter Test Upgrade system DB here */
SET #TestUpgradeDB = 'TESTzSBSSYS'
--set #Use = 'USE ' + #NewProdDB + ';SELECT name FROM sys.tables'
--EXEC (#Use)
SET NOCOUNT ON
set #rescanCode = 'DECLARE recscan CURSOR FOR
SELECT TABLE_NAME FROM ' + #TestUpgradeDB + '.INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME NOT LIKE ''Mbf%'' AND TABLE_TYPE = ''BASE TABLE''
ORDER BY TABLE_NAME'
exec (#rescanCode)
OPEN recscan
FETCH NEXT FROM recscan INTO #ListOfTables
WHILE ##fetch_status = 0
BEGIN
BEGIN TRY
/* START Table column query */
Declare #Table varchar(60)
set #Table = #ListOfTables
set #table = (SELECT top 1 name FROM sys.tables where name = #Table)
DECLARE
#sql1 nvarchar(max) = ''
,#INTOColumns NVARCHAR(MAX)=''
,#Where nvarchar(max) = ''
,#ColumnID Int
,#Column Varchar(8000)
,#Type Varchar(8000)
,#Length Int
,#del1 varchar(2) = ','
,#CRLF bit = 1
,#aliasfield varchar(5) = '[a].'
DECLARE CSR_Attributes CURSOR FOR
SELECT
[ColumnID] = Col.column_id,
[Column] = Col.Name,
[Type] = [types].name,
[Length] = Col.max_length
FROM sys.objects Obj, sys.columns Col, sys.types [types]
WHERE Obj.OBJECT_ID = Col.OBJECT_ID AND Obj.TYPE = 'U'
AND Col.system_type_id = [types].system_type_id
AND Obj.name = #table
AND Col.name <> 'tstamp'
ORDER BY Obj.name, Col.column_id, Col.name
OPEN CSR_Attributes
FETCH NEXT FROM CSR_Attributes INTO #ColumnID, #Column, #Type, #Length
WHILE ##FETCH_STATUS = 0
BEGIN
set #sql1 += #column + #del1
set #Where += 'b.' + #column + '=a.' + #column + ' and '
set #INTOColumns += '#INTOcol,'
FETCH NEXT FROM CSR_Attributes INTO #ColumnID, #Column, #Type, #Length
END
CLOSE CSR_Attributes
DEALLOCATE CSR_Attributes
SET #Columns = SUBSTRING(#sql1,1,len(#sql1)-1) -- get rid of last comma
SET #Where = SUBSTRING(#Where,1,len(#Where)-4) -- get rid of last 'and'
SET #INTOColumns = SUBSTRING(#INTOColumns,1,len(#INTOColumns)-1) -- get rid of last comma
/* END Table column query */
/* Create SELECT statement here */
SET #ResultsTest='SELECT TOP 1 ' + #Columns + '
FROM ' + #TestUpgradeDB + '..' + #Table + ' A
WHERE NOT EXISTS
(SELECT ' + #Columns + '
FROM ' + #NewProdDB + '..' + #Table + ' B WHERE ' + #Where + ')'
SET #SetResultsCursor = 'DECLARE DataReturned CURSOR FOR ' + #ResultsTest
exec (#SetResultsCursor)
OPEN DataReturned
SET #Fetcher = 'DECLARE #INTOcol NVARCHAR(Max)
FETCH NEXT FROM DataReturned INTO ' + #INTOColumns
exec (#Fetcher)
if ##FETCH_STATUS = 0
begin
CLOSE DataReturned
DEALLOCATE DataReturned
SET #Query='SELECT ' + #Columns + '
FROM ' + #TestUpgradeDB + '..' + #Table + ' A WHERE NOT EXISTS
(SELECT ' + #Columns + ' FROM ' + #NewProdDB + '..' + #Table + ' B WHERE ' + #Where + ')'
select #Table
exec (#Query)
end
else
begin
CLOSE DataReturned
DEALLOCATE DataReturned
end
end try
begin catch
--SELECT ERROR_MESSAGE() AS ErrorMessage;
end catch
FETCH NEXT FROM recscan INTO #ListOfTables
end
CLOSE recscan
DEALLOCATE recscan
SET NOCOUNT OFF
You can't do this:
DECLARE #DB varchar(10) = 'beep';
DECLARE #USE varchar(50) = 'USE '+ #DB;
EXEC sp_sqlexec #USE;
SELECT blah FROM bloop
Database context is only used during the #USE sql, then reverts
You can do this:
DECLARE #DB varchar(10) = 'beep';
DECLARE #SQL varchar(50) = 'USE '+#DB+'; SELECT blah FROM bloop;'
EXEC sp_sqlexec #USE;
That aside, look into SQL Server Data Tools (SSDT)
It does exactly what it seems you are trying to do, schema and/or data compare between databases, and it's very easy to use.
I am new to this SQL scripting.
Getting error while trying to execute a delete command.
Msg 8169, Level 16, State 2, Line 52 Conversion failed when converting
from a character string to uniqueidentifier.
And the script which I want to execute is:
-- attachments cleardown script
-- SJM 18/09/2009
set nocount on
declare #tableName nvarchar(200)
declare #columnName nvarchar(200)
declare #moduleName nvarchar(200)
declare #objectName nvarchar(200)
declare #attributeName nvarchar(200)
declare #dynamicSQL nvarchar(500)
declare #attachXML varchar(2000)
declare #fileGuid varchar(36)
declare #deletedXML varchar(100)
set #deletedXML = '<DataObjectAttachment><FileName>Deleted</FileName></DataObjectAttachment>'
declare attachCursor cursor fast_forward for
select t5.md_name, t4.md_name, t3.md_title, t2.md_title, t1.md_title
from md_attribute_type t1
join md_class_type t2 on t1.md_class_type_guid = t2.md_guid
join md_module t3 on t2.md_module_guid = t3.md_guid
join md_database_column t4 on t1.md_database_column_guid = t4.md_guid
join md_database_table t5 on t2.md_database_table_guid = t5.md_guid
where t1.md_data_type = 16 and (
t1.md_defined_by = 2 or
t1.md_guid in ('103DBEAB-252F-4C9A-952A-90A7800FFC00', '2515E980-788D-443D-AA89-AA7CC3653867',
'2D29495E-785E-4062-A49C-712A8136EBC7', '6A204C77-1007-48CC-B3BC-077B094540AE',
'9A24BFEF-2CAB-4604-8814-656BA0B9ECC3', 'C368CB18-B4C4-4C4F-839C-F7E6E1E17AA8',
'0814586B-A11E-4129-AF9B-9EC58120C9AF', 'BD4F73C4-07CA-4DC2-86AD-D713FBC6E7BA')
)
and t2.md_behaviour not in (2, 4, 8) -- exclude reference lists
and t2.md_guid not in (select b.md_class_type_guid from md_class_behaviour b where b.md_behaviour_type_guid in
(select bt.md_guid from md_behaviour_type bt where bt.md_name in ('Category','Ranked'))) -- exclude categories and ordered lists
and t3.md_name != 'Lifecycle'
order by t3.md_title, t2.md_title, t1.md_title
open attachCursor
fetch next from attachCursor into #tableName, #columnName, #moduleName, #objectName, #attributeName
while (##FETCH_STATUS = 0)
begin
print 'Deleting from ' + #moduleName + ' -> ' + #objectName + ' (' + #tableName + ') -> ' + #attributeName + ' (' + #columnName + ')...'
set #dynamicSQL = 'declare attachCursor1 cursor fast_forward for'
set #dynamicSQL = #dynamicSQL + ' select ' + #columnName + ' from ' + #tableName
set #dynamicSQL = #dynamicSQL + ' where ' + #columnName + ' != ''' + #deletedXML + ''''
exec sp_executesql #dynamicSQL
open attachCursor1
fetch next from attachCursor1 into #attachXML
while (##FETCH_STATUS = 0)
begin
set #fileGuid = substring(#attachXML, charindex('<Guid>', #attachXML) + 6, 36)
delete from tps_attachment_data where tps_guid = convert(uniqueidentifier, #fileGuid)
fetch next from attachCursor1 into #attachXML
end
close attachCursor1
deallocate attachCursor1
set #dynamicSQL = 'update ' + #tableName + ' set ' + #columnName + ' = ''' + #deletedXML + ''''
set #dynamicSQL = #dynamicSQL + ' where ' + #columnName + ' != ''' + #deletedXML + ''''
exec sp_executesql #dynamicSQL
print '- Deleted ' + convert(varchar(10),##Rowcount) + ' records.'
fetch next from attachCursor into #tableName, #columnName, #moduleName, #objectName, #attributeName
end
close attachCursor
deallocate attachCursor
set nocount off
print char(13) + 'Attachment cleardown complete.'
print char(13) + 'Next steps to reclaim data file space:'
print '1. Take a backup!'
print '2. Shrink the database using the command: DBCC SHRINKDATABASE(''' + convert(varchar(100),SERVERPROPERTY('ServerName')) + ''')'
print '3. Put the database into SINGLE_USER mode (Properties -> Options -> Restrict Access)'
print '4. Detach the database'
print '5. Rename the database .LDF log file'
print '6. Re-attach the database using single file method'
When I parse above script then it is completing successfully but on execution it throws the error.
There are two new functions that have been available since SQL Server 2012: TRY_CAST and TRY_CONVERT, which complement the existing CAST and CONVERT functions.
If you cast an empty string to a unique identifier:
SELECT CAST('' as uniqueidentifier) uid
This would result in the error you are seeing. The same would be true or other strings that aren't GUIDs. Use TRY_CAST instead and the function returns a NULL instead of throwing an error. You can then skip records that don't have a valid GUID.
begin
set #fileGuid = substring(#attachXML, charindex('<Guid>', #attachXML) + 6, 36)
DECLARE #fileGuidOrNull uniqueidentifier = try_convert(uniqueidentifier, #fileGuid)
IF #fileGuidOrNull IS NOT NULL
delete from tps_attachment_data where tps_guid = #fileGuidOrNull
fetch next from attachCursor1 into #attachXML
end
I am trying to build an email and have run into an issue. When the stored procedure runs, I get the following error message.
Msg 14624, Level 16, State 1, Procedure sp_send_dbmail, Line 242
At least one of the following parameters must be specified. "#body,
#query, #file_attachments, #subject".
My code is below but I am adding each of the requested items. I have narrowed down where the breakdown happens. If I pull out the concatenation "+" everything works as expected. But I have done this before with the concatenation so I am not sure what is different.
DECLARE #RespPeriod varchar(20)
DECLARE #SubjectLine varchar(100)
DECLARE #ContactEmail varChar(100)
DECLARE #AAEAPVSupplierID int
DECLARE #key varchar(50)
DECLARE #formattedURL varchar(100)
DECLARE #emailBody varchar(max)
DECLARE Curs Cursor
FOR
SELECT theID FROM #temptbl
OPEN Curs
FETCH NEXT FROM Curs INTO #theID
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT *
INTO #temptbl
FROM tblmainTbl
WHERE theID = #theID
DECLARE #isComplete Bit = 1
IF EXISTS (SELECT * FROM #temptbl WHERE Complete = 0)
BEGIN
SET #isComplete = 0
END
IF #isComplete = 1
BEGIN
SET #SubjectLine = 'Testing ' + #RespPeriod + ' Testing.'
SET #ContactEmail = (SELECT SalesEmail FROM #temptbl WHERE theID = #theID)
SET #key = (SELECT ResponseKEY FROM #temptbl WHERE theID = #theID)
SET #formattedURL = 'http://www.something.com/something.aspx?rkey=' + #key
SET #emailBody = '<html>Dear BlaBlaBla' + #RespPeriod + ' ' + #formattedURL + '">' + #formattedURL + '</a></html>'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'SMTPProfile'
,#recipients = #ContactEmail
,#subject = #SubjectLine
,#body = #emailBody
,#body_format = 'HTML'
END
DROP TABLE #temptbl
FETCH NEXT FROM Curs INTO #theID
END
CLOSE Curs
DEALLOCATE Curs
Your code sample is incomplete (you're lacking the declaration of some of the variables used). My hunch is one or more of the variable values (maybe #RespPeriod?) is NULL, and when you do the concatenations for the variable assignments used in your sp_send_dbmail call, you're passing NULL.
Remember, string + NULL = NULL
Right before your call to the sp_send_dbmail, insert these statements...
PRINT '--------------'
PRINT '#SubjectLine = ' + ISNULL(#SubjectLine, 'NULL')
PRINT '#ContactEmail = ' + ISNULL(#ContactEmail, 'NULL')
PRINT '#key = ' + ISNULL(#key, 'NULL')
PRINT '#formattedURL = ' + ISNULL(#formattedURL, 'NULL')
PRINT '#emailBody = ' + ISNULL(#emailBody, 'NULL')
PRINT '--------------'
It should quickly become apparent if this is your cause. If it is, chase back the individual parts of whatever variables are resolving as NULL until you find the piece that caused the entire string to be NULL. If it is not, please provide more code so we can look somewhere else.
I have following stored procedure which basically uses cursor to get people who have appointments today and sends them email. For some reason this query won't complete. When I try to execute it, it just spins and I had to stop it. I let it run for as long as 7 minutes once and still I didn't get either an error or timeout. Not sure what it is doing. Any help will be appreciated. Here is my query:
ALTER PROCEDURE [dbo].[spReminderEmail]
AS
SET NOCOUNT ON;
DECLARE #MyCursor CURSOR
DECLARE #emailBody nvarchar(max)
DECLARE #subject nvarchar(max)
DECLARE #recipients nvarchar(max)
DECLARE #appointmentDate datetime
DECLARE #doctorFirstName nvarchar(max)
DECLARE #doctorLastName nvarchar(max)
DECLARE #groupName nvarchar(max)
DECLARE #location nvarchar(max)
DECLARE #count int
SET #count = 0
SET #MyCursor = CURSOR FAST_FORWARD For
Select StartTime, PersonEmail, DoctorFirstName, DoctorLastName, GroupName, Location from vwAppointment where StartTime BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)) AND IsActive = 1
Open #MyCursor
FETCH NEXT FROM #MyCursor INTO #appointmentDate, #recipients, #doctorFirstName, #doctorLastName, #groupName, #location
WHILE ##FETCH_STATUS = 0
BEGIN
SET #emailBody = 'Hello from ' + #groupName + '. This is an email reminder of your appointment with ' + #doctorFirstName + ' ' + #doctorLastName + ' on ' + convert(varchar, #appointmentDate, 1) + ' at ' + #location + '.' + CHAR(13) + CHAR(10) + 'To help facilitate the meeting, please remember to bring with you any relevant documents (ID, insurance, etc.) and be prepared with questions for the office.' + CHAR(13) + CHAR(10) + 'If you are unable to make the appointment, please call ' + #groupName + ' or return to KSUAdvising and use the cancellation function. Cancellations are requested at least a day in advance.' + CHAR(13) + CHAR(10) + 'Late Policy:' + CHAR(13) + CHAR(10) + 'some text here...';
SET #subject = 'REMINDER: Your Appointment with the ' + #groupName;
SET #count = #count + 1
END
CLOSE #MyCursor
DEALLOCATE #MyCursor
PRINT #count
if (#count > 0)
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#profile_name='my_profile',
#recipients=#recipients,
#body=#emailBody,
#subject=#subject
END
Inside the WHILE loop (before END line) you must add this:
FETCH NEXT FROM #MyCursor INTO #appointmentDate, #recipients,
#doctorFirstName, #doctorLastName, #groupName, #location
to scroll for every loop a record of your query
You're never fetching your next row. So your loop will go on forever doing nothing. You need to add FETCH NEXT FROM #MyCursor INTO #appointmentDate, #recipients, #doctorFirstName, #doctorLastName, #groupName, #location right before your END statment . See the example at the bottom of This
You also may try to debug your sp to find exact place of issues in you SP in the future.