Inserting whole sql script in variable - sql

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'

Related

Cursor won't fetch 2nd Value

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

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

Incorrect syntax near 'db_cursor'

I am getting the 'Incorrect syntax near 'db_cursor' error when attempting to run the below query. Can someone please tell me why and where my error in the scripting? Thanks in advance!
declare #Sort varchar(4000)
declare #OpenDate datetime
declare #ret int;
set #Sort = 'All'
set #OpenDate = '1/1/2015'
IF (#Sort = 'All')
BEGIN
declare #Organization varchar(2500)
declare #OrgEmp int
Set #OrgEmp = 0
Set #ret = 0
declare db_cursor CURSOR FOR
SELECT distinct RTrim(Organization) + '|' as Oganization,
(select rpt.ufnGetEmployeePopulation(RTrim(Organization) + '|', #OpenDate)) as NumberofEmployee FROM dbo.CorpStartEndDates where EndDate >= #OpenDate
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #Organization, #OrgEmp
WHILE ##FETCH_STATUS = 0
BEGIN
Set #ret = #ret + #OrgEmp
FETCH NEXT FROM db_cursor INTO #Organization, #OrgEmp
END
CLOSE db_cursor
DEALLOCATE db_cursor
You're missing an END
if the cursor is inside the first BEGIN/END then put END after the DEALLOCATE
If the cursor is outside of the first begin/end, but the end before the OPEN
so..
declare #Sort varchar(4000)
declare #OpenDate datetime
declare #ret int;
set #Sort = 'All'
set #OpenDate = '1/1/2015'
IF (#Sort = 'All')
BEGIN
declare #Organization varchar(2500)
declare #OrgEmp int
Set #OrgEmp = 0
Set #ret = 0
declare db_cursor CURSOR FOR
SELECT distinct RTrim(Organization) + '|' as Oganization,
(select rpt.ufnGetEmployeePopulation(RTrim(Organization) + '|', #OpenDate)) as NumberofEmployee FROM dbo.CorpStartEndDates where EndDate >= #OpenDate
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #Organization, #OrgEmp
WHILE ##FETCH_STATUS = 0
BEGIN
Set #ret = #ret + #OrgEmp
FETCH NEXT FROM db_cursor INTO #Organization, #OrgEmp
END
CLOSE db_cursor
DEALLOCATE db_cursor
END
or
IF (#Sort = 'All')
BEGIN
declare #Organization varchar(2500)
declare #OrgEmp int
Set #OrgEmp = 0
Set #ret = 0
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 ;

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 '.