Cursor won't fetch 2nd Value - sql

Hei folks,
I got a little problem with TSQL and a cursor. My cursor is suppose to loop through a list (view) of mailadresses. My Code goes like this:
set #sqlstatement = 'Declare cur CURSOR FOR SELECT ' + #col + '
FROM ' + #view + ' group by ' + #col
exec sp_executesql #sqlstatement
OPEN cur
FETCH NEXT FROM cur INTO #emailAddress
WHILE ##FETCH_STATUS = 0 BEGIN
SET #MyRecipients = #emailAddress;
SET #MyResult = Replace(#MyResult,'defg',#emailAddress)
SELECT #MyResult
IF ##ROWCOUNT > 0
begin
EXEC dbo.[Excel] #html = #html OUTPUT,#query = #MyResult
IF #html != ''
begin
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Operator',
#recipients= #MyRecipients,
#body = #html,
#body_format = 'HTML',
#subject= #MySubject,
#copy_recipients = #MyCC
;
END
END
FETCH NEXT FROM cur INTO #emailAddress
END
Close cur
DEALLOCATE cur
So my problem is that the cursor does run 2 times if there are 2 mailadresses in the view, but I get 2 times the same mail instead of 2 different mails. (I'm part of the CC to see if it works)
Hope someone has some ideas and can help me.
Greetings,
Soul

I have gone through your problem and I have also executed the cursor used by you and it is working fine. As per my understanding following code could have created the problem.
SET #MyResult = Replace(#MyResult,'defg',#emailAddress)
I think it was not able to replace the email address of the previous iteration due to which the issue is occurring. It seems that here you want to replace the email address of the previous iteration with the email address of current iteration so following code might help.
SET #oldEmailAddress = 'defg'
set #sqlstatement = 'Declare cur CURSOR FOR SELECT ' + #col + '
FROM ' + #view + ' group by ' + #col
exec sp_executesql #sqlstatement
OPEN cur
FETCH NEXT FROM cur INTO #emailAddress
WHILE ##FETCH_STATUS = 0 BEGIN
SET #MyRecipients = #emailAddress;
SET #MyResult = Replace(#MyResult,#oldEmailAddress,#emailAddress)
SELECT #MyResult
IF ##ROWCOUNT > 0
begin
EXEC dbo.[Excel] #html = #html OUTPUT,#query = #MyResult
IF #html != ''
begin
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Operator',
#recipients= #MyRecipients,
#body = #html,
#body_format = 'HTML',
#subject= #MySubject,
#copy_recipients = #MyCC
;
END
END
SET #oldEmailAddress = #emailAddress
FETCH NEXT FROM cur INTO #emailAddress
END
Close cur
DEALLOCATE cur

Related

SQL Server - Cursor Error

I am declaring a dynamic cursor due to a nesting of the stored procedure based on a parent-child relationship of the data that can go multiple levels and vary daily when processed. The stored procedure works for the parent call, however the process of this procedure for child data causes a message stating that the "Cursor is not open." This message occurs on the Fetch which is immediately after checking to be sure the cursor is open.
DECLARE #OutCur CURSOR;
DECLARE #curName as NVARCHAR(MAX);
...
SET #curName = LEFT(replace(replace(CONVERT (time, GETDATE()),':',''),'.',''),8);
SET #sqlCommand = 'SELECT a.myfields FROM mytable a;
SET #sqlCommand = 'SET #cursor' + #curName + ' = CURSOR LOCAL FAST_FORWARD FOR ' + #sqlCommand + ' OPEN #cursor' + #curName + ';'
SET #curName = '#cursor' + #curName + ' cursor output';
EXEC sys.sp_executesql #sqlCommand,#curName,#OutCur output
IF CURSOR_STATUS('global','#OutCur')=-1
OPEN #OutCur;
FETCH NEXT FROM #OutCur INTO #name,#type
Thanks in advance for the input.
if you uncomment close+deallocate - script works fine:
GO
DECLARE #OutCur CURSOR;
DECLARE #curName as NVARCHAR(MAX), #sqlCommand nvarchar(max), #name varchar(100), #type varchar(100)
declare #i int = 0
while #i < 5
begin
SET #curName = LEFT(replace(replace(CONVERT (time, GETDATE()),':',''),'.',''),8);
SET #sqlCommand = 'SELECT ''111'' as name, ''cc'' as type; '
SET #sqlCommand = 'SET #cursor' + #curName + ' = CURSOR LOCAL FAST_FORWARD FOR ' + #sqlCommand + ' OPEN #cursor' + #curName + ';'
SET #curName = '#cursor' + #curName + ' cursor output';
EXEC sys.sp_executesql #sqlCommand,#curName,#OutCur output
FETCH NEXT FROM #OutCur INTO #name,#type
select #name, #type
--close #OutCur
--deallocate #OutCur
set #i += 1
end
GO

Inserting whole sql script in variable

I have problem inserting sql script in the variable.I have this code
declare #result_var varchar(max);
SET #result_var='';
DECLARE #cursor CURSOR,
#name VARCHAR(100)
SET #cursor = CURSOR
FOR SELECT [NAME]
FROM [iflvs08].mds.mdm.lv_budget_employee
OPEN #cursor
FETCH next FROM #cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
IF (RIGHT(#Name, 1) = ' ')
begin
IF( Len(#result_var) > 1 )
SET #result_var=#result_var + ','+ #name
ELSE
SET #result_var=#name
END
FETCH next FROM #cursor INTO #name
END
I want to insert into variable it but when try to insert it like this
set #sql='code here'
It get confuse whit this ' symbol and dont insert it
I always get error like this
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near '
begin
IF( Len(#result_var) > 1 )
SET #result_var=#result_var + '.
basically you have to replace all ' symbols with ''
set #sql = '
declare #result_var varchar(max);
SET #result_var='''';
DECLARE #cursor CURSOR,
#name VARCHAR(100)
SET #cursor = CURSOR
FOR SELECT [NAME]
FROM [iflvs08].mds.mdm.lv_budget_employee
OPEN #cursor
FETCH next FROM #cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
IF (RIGHT(#Name, 1) = '' '')
begin
IF( Len(#result_var) > 1 )
SET #result_var=#result_var + '',''+ #name
ELSE
SET #result_var=#name
END
FETCH next FROM #cursor INTO #name
END'

Problems with output parameter

I have problem when I run this procedure it gives me back an error trying to parse 'ok' to int but I dont want result to be int.
DECLARE #result_var nvarchar(max)
DECLARE #ParmDefinition NVARCHAR(max)
EXECUTE Sp_executesql
#definition,
#ParmDefinition,
#result_var = #result_var output;
Code that is changing #result_var
SET #result_var = ''ok'';
DECLARE #cursor CURSOR,
#name VARCHAR(100)
SET #cursor = CURSOR FOR
SELECT [NAME]
FROM [iflvs08].mds.mdm.lv_budget_employee
OPEN #cursor
FETCH next FROM #cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
IF RIGHT(#Name, 1) = '' ''
begin
IF (Len(#result_var) > 1)
SET #result_var = #result_var + '','' + #name
ELSE
SET #result_var = #name
END
FETCH next FROM #cursor INTO #name
END
Looks like that you declared but didn't set up #ParmDefinition variable.
It should be like this:
DECLARE #ParmDefinition NVARCHAR(max)
SET #ParmDefinition = N'#result_var nvarchar(max) OUTPUT';
EXECUTE Sp_executesql
#definition,
#ParmDefinition,
#result_var=#result_var output ;

How to loop the variables in t-sql

I have a t-sql i have to loop the variables.
DECLARE #empno nVARCHAR(MAX),#tableHTML NVARCHAR(MAX) ;
set #empno = (select Employee_No from emptemp where active = 'Yes');
SET #tableHTML =
N'<H2>Additions</H2>' +
N'<table border="1">' +
N'<th>Ename</th>' +
N'<th>Sal</th>' +
'<tr>' +
CAST ( ( select td=ename,'',td=sal,'' from emp Where empno = #empno)
FOR XML PATH('tr'), TYPE ) AS NVARCHAR(MAX) ) + N'</table>' ;
EXEC msdb.dbo.sp_send_dbmail
#recipients=someone#gmail.com,
#subject = emp ,
#body = #tableHTML , #body_format = 'HTML',
#profile_name = 'Sql Profile'
The Emptemp table looks like
id empno active
1 245 yes
2 124 yes
3 255 yes
4 224 No
I have to send the individual mail based on the data in emp table
That is how cursor will look like:
DECLARE #empno nVARCHAR(MAX)
DECLARE #tableHTML NVARCHAR(MAX) ;
DECLARE #ID INT;
DECLARE Curs CURSOR FAST_FORWARD
FOR
SELECT DISTINCT ID
FROM dEmptemp
WHERE active = 'Yes'
ORDER BY ID
OPEN Curs
FETCH NEXT FROM Curs INTO #ID
WHILE ##FETCH_STATUS = 0
BEGIN
set #empno = (SELECT empno FROM emptemp WHERE ID = #ID);
SET #tableHTML =
N'<H2>Additions</H2>' +
N'<table border="1">' +
N'<th>Ename</th>' +
N'<th>Sal</th>' +
'<tr>' +
CAST ( ( select td=ename,'',td=sal,'' from emp Where empno = #empno)
FOR XML PATH('tr'), TYPE ) AS NVARCHAR(MAX) ) + N'</table>' ;
EXEC msdb.dbo.sp_send_dbmail
#recipients=someone#gmail.com,
#subject = emp ,
#body = #tableHTML , #body_format = 'HTML',
#profile_name = 'Sql Profile'
FETCH NEXT FROM Curs INTO #ID
END
CLOSE Curs
DEALLOCATE Curs;

Invalid Column Name '#FileName-- value'

I am getting 'Invalid Column Name '#FileName-- value'' ERROR WHILE executing below stored procedure. I tried to find the root cause of the issue with no luck...Please suggest me where i am wrong.
ALTER PROCEDURE [dbo].[usp_ICLExtract_GetFile]
#FileName Varchar(50),
#Image_Path Varchar(50) Output,
#FIleNameList varchar(4096) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #strProcName varchar(255)
SET #strProcName = 'usp_ICLExtract_GetFile'
DECLARE #strSQL1 varchar(1024), #strSQL2 varchar(1024)
DECLARE #strFileName Varchar(50)
DECLARE #intErrorReturn int
SET #intErrorReturn = 0
SET #FileNameList = ''
SET #Image_Path = ''
SET #strSQL1 = N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID = [tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ' + #FileName --This line cause error
/*==============================================================================
* Run the query'
*==============================================================================*/
SET #strSQL2 = 'DECLARE curCategory INSENSITIVE SCROLL CURSOR FOR ' + #strSQL1
EXEC(#strSQL2)
SELECT #intErrorReturn = ##ERROR
IF (#intErrorReturn <> 0) GOTO usp_ICLExtract_GetFile_Error
OPEN curCategory
SELECT #intErrorReturn = ##ERROR
IF (#intErrorReturn <> 0) GOTO usp_ICLExtract_GetFile_Error
FETCH NEXT FROM curCategory INTO #strFileName
WHILE (##FETCH_STATUS <> -1)
BEGIN
SET #FileNameList = #FileNameList + #strFileName + ';'
SET #Image_Path = #Image_Path + 1
FETCH NEXT FROM curCategory INTO #strFileName
END
CLOSE curCategory
DEALLOCATE curCategory
RETURN(0)
usp_ICLExtract_GetFile_Error:
RETURN(#intErrorReturn)
END
replace line with this
SET #strSQL1 = N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID = [tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ''' + #FileName +'''
Change your query to this:
N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter
INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID =
[tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ''' + #FileName + ''''
you have to pass value between apostrophes '.