SQL Server Stored Procedure with cursor - sql-server

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.

Related

Is there a way in SQL (SQL Server) to find out a column, that could work as a unique key for the table?

I have two csv files made of a table of a database.
One is one month older backup than the other.
I need to find differences in them by comparing the two csv:s
Normally I'd use the first column, the id, as the unique identifier, as the
key to compare the rows with, but in this case it is not available.
The table has dozens of columns so surely there would be one that has only
unique values. Meaning that no two or more rows have the same value in that
column.
Is there an SQL query or any way to find out a column in a table that doesn't have duplicates on any row? Hence, that column could be used as the unique identifier of a row. The database is SQL Server 2012.
You can write a script to group by all the columns individually and see the count. You can find the fields which are most distinct. You can combine the fields to make it more distinct. Good Luck!
I used this script for similar purpose:
USE [Database]
DECLARE #name sysname
DECLARE #cntAll int
DECLARE #cntDist int
DECLARE #cntNull int
DECLARE #err int
DECLARE #stm nvarchar(max)
DECLARE #tblName sysname
SET #tblName = 'Table'
-- All rows
SET #stm = N'SELECT #cntAll = COUNT(*) FROM dbo.[' + #tblName + ']'
EXEC #err = sp_executesql #stm, N'#cntAll int OUTPUT', #cntAll OUTPUT
IF #err <> 0 BEGIN
RETURN
END
-- Distinct rows by column
DECLARE columns_tables CURSOR GLOBAL FORWARD_ONLY READ_ONLY FOR
SELECT [name] FROM sys.columns WHERE object_id = OBJECT_ID('dbo.[' + #tblName + ']')
OPEN columns_tables
FETCH NEXT FROM columns_tables INTO #name
WHILE (##FETCH_STATUS = 0) BEGIN
SET #stm =
N'SELECT #cntDist = COUNT(DISTINCT [' + #name + ']) '+
'FROM dbo.[' + #tblName + '] '+
'WHERE [' + #name + '] IS NOT NULL'
EXEC #err = sp_executesql #stm, N'#cntDist int OUTPUT', #cntDist OUTPUT
IF #err <> 0 BEGIN
CLOSE columns_tables
DEALLOCATE columns_tables
BREAK
END
SET #stm =
N'IF EXISTS (' +
'SELECT ([' + #name + ']) '+
'FROM dbo.[' + #tblName + '] '+
'WHERE [' + #name + '] IS NULL'+
') SET #cntNull = 1 '+
'ELSE SET #cntNull = 0'
EXEC #err = sp_executesql #stm, N'#cntNull int OUTPUT', #cntNull OUTPUT
IF #err <> 0 BEGIN
CLOSE columns_tables
DEALLOCATE columns_tables
BREAK
END
IF (#cntAll = #cntDist) AND (#cntNull = 0) BEGIN
PRINT 'Possible column ' + #name
END
FETCH NEXT FROM columns_tables INTO #name
END
CLOSE columns_tables
DEALLOCATE columns_tables

T-SQL context issue

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.

Msg 8169, Level 16, State 2, Line 52 Conversion failed when converting from a character string to uniqueidentifier

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

T-SQL string email format issue

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.

Search database through Views

I m trying to search database values through the views.
I m stuck at the below error.
USE AdventureWorks
GO
--EXEC Customer.sp_FindInViews Stephen, Sales
ALTER PROCEDURE Customer.sp_FindInViews #stringToFind VARCHAR(100), #schema sysname
AS
SET NOCOUNT ON
DECLARE
#ViewName AS nVarChar(128)
, #TmpQuery AS nVarChar(500)
, #Out3 as int
, #sqlCommand VARCHAR(8000)
, #where VARCHAR(8000)
, #columnName sysname
, #cursor VARCHAR(8000)
DECLARE Outer_Cursor CURSOR FOR
SELECT schema_name(schema_id)+'.'+name as "View_Name",schema_id FROM [sys].[all_views]
where schema_id in (#schema)
OPEN Cur_Views
FETCH NEXT FROM Cur_Views INTO #ViewName
WHILE ##Fetch_Status = 0
BEGIN
SET #sqlCommand = 'SELECT * FROM ' + #ViewName + ' WHERE'
SET #where = ''
DECLARE col_cursor CURSOR FOR
SELECT syscolumns.name FROM sys.sysobjects "sysobjects"
INNER JOIN sys.syscolumns "syscolumns"
on syscolumns.id = sysobjects.id
WHERE (sysobjects.type = 'V' and SCHEMA_NAME(sysobjects.uid) + '.' +sysobjects.name = #ViewName)
OPEN col_cursor
FETCH NEXT FROM col_cursor INTO #columnName
WHILE ##FETCH_STATUS = 0
BEGIN
IF #where <> ''
SET #where = #where + ' OR'
---------------------------------------------------------------------------
SET #where = #where + ' ' + #columnName + ' LIKE ''' + #stringToFind + ''''
SET #sqlCommand = #sqlCommand + #where
CREATE TABLE #Data (var varchar)
SELECT #TmpQuery = #sqlCommand
INSERT #Data exec (#TmpQuery)
SELECT #Out3 = var from #Data
PRINT #Out3
DROP TABLE #Data
FETCH NEXT FROM col_cursor INTO #columnName
END
CLOSE col_cursor
DEALLOCATE col_cursor
CLOSE Outer_Cursor
DEALLOCATE Outer_Cursor
END
GO
The code compiles , but it does give the error when executed as below :
EXEC Customer.sp_FindInViews Stephen, Sales
Msg 16915, Level 16, State 1, Procedure sp_FindInViews, Line 19
A cursor with the name 'Outer_Cursor' already exists.
Msg 16905, Level 16, State 1, Procedure sp_FindInViews, Line 22
The cursor is already open.
Msg 16924, Level 16, State 1, Procedure sp_FindInViews, Line 23
Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.
I m not sure , why I m getting this error. I feel i m handling them. Any input on this , would be helpful.
Thanks.
Looks to me that you've changed cursor names. You start by declaring Outer_Cursor then open a cursor called Cur_Views.
Also when you fetch from the cursor you are only putting the cursor values in to 1 variable, in the cursor declaration you list 2 fields (View_Name and schema_id).
DECLARE Outer_Cursor CURSOR FOR
SELECT schema_name(schema_id)+'.'+name as "View_Name",schema_id FROM [sys].[all_views]
where schema_id in (#schema)
OPEN Cur_Views
FETCH NEXT FROM Cur_Views INTO #ViewName
The "cursor is already open" errors occur when you run the procedure a second time becuase the original cursors are still open (as the first attempt errored before being able to close them).
Not sure if it's the answer you've been looking for, but SQLSearch (http://www.red-gate.com/products/sql-development/sql-search/) is an excellent tool for searching databases (of course, you can set it to search views only) and it's free...

Resources