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
Related
How to select 100000187 from 100000187^Visit-NCH in sql?
I use below function for similar functionality.
CREATE FUNCTION [dbo].[fn_Get_Integer_Part]
(
#strAlphaNumeric VARCHAR(256)
)
RETURNS bigint
AS
BEGIN
DECLARE #intAlpha INT;
SET #intAlpha = PATINDEX('%[^0-9]%', #strAlphaNumeric);
BEGIN
WHILE #intAlpha > 0
BEGIN
SET #strAlphaNumeric = STUFF(
#strAlphaNumeric ,
#intAlpha ,
1 ,
'');
SET #intAlpha = PATINDEX('%[^0-9]%', #strAlphaNumeric);
END;
END;
RETURN RIGHT('000000000000' + ISNULL(#strAlphaNumeric, 0), 12)
END;
Usage:
SELECT dbo.fn_Get_Integer_Part('100000187^Visit-NCH');
Result:
100000187
Given your comment in OP,
I want everything before '^'
The following query is what you seek:
SELECT LEFT(<column>, CHARINDEX('^',<column>)-1) AS 'Stripped Column' FROM <table>
CREATE FUNCTION [dbo].[REMOVE_NONINTEGERS](#TEXT VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #Reset BIT;
DECLARE #Ret VARCHAR(8000);
DECLARE #i INT;
DECLARE #c CHAR(1);
DECLARE #CharLength INT
DECLARE #CHARSTART INT
DECLARE #RESULT VARCHAR(MAX)
SET #I = 1
SET #CHARSTART = 0
WHILE (#i <= LEN(#Text))
BEGIN
SET #CHARSTART = #CHARSTART + 1
SET #RET = SUBSTRING(#TEXT,#CHARSTART,1)
IF(#RET NOT in('0','1','2','3','4','5','6','7','8','9'))
BEGIN
SET #RET = ISNULL(#RET,'')
SET #I = #I + 1
END
ELSE
BEGIN
SET #RESULT = ISNULL(#RESULT,'') + #RET
SET #I = #I + 1
END
END
RETURN #RESULT
END
SELECT [dbo].[REMOVE_NONINTEGERS]('100000187^Visit-NCH')
I have one parent stored procedure and one nested stored procedure. Parent Stored procedure calls the nested stored procedure on loop. Now when there is certain condition matches I have raised the error. When this error is raised I want to stop all the process and return the error.
CREATE Proc [dbo].[Usp_GenSalarySheet](#SalData [HRM].UTDT_SalaryData ReadOnly)
AS
set nocount on
DECLARE #SMT NVARCHAR(MAX)
SET #SMT = 'Create Table ##SalarySheet (StaffID INT,FullName NVARCHAR(1024),PresentDays NVARCHAR(1024),Absent NVARCHAR(1024),Department NVARCHAR(1024),Designation NVARCHAR(1024),'
DECLARE #HopName nvarchar(max)
Declare HOPCursor cursor for select ID from HRM.tbl_HOP
OPEN HOPCursor
FETCH NEXT FROM HOPCursor INTO #HopName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SMT = #SMT + ' [' + #HopName + '] DECIMAL(19,7),'
FETCH NEXT FROM HOPCursor into #HopName
END
SET #SMT = #SMT + '[Total] DECIMAL(19,7))'
CLOSE HOPCursor
DEALLOCATE HOPCursor
print (#smt)
exec (#SMT)
select * into #temp from #SalData
Declare #TopID INT
While (Select Count(*) From #Temp) > 0
Begin
Select Top 1 #TopID = StaffID From #temp
Declare #StaffID INT =(select top 1 StaffID from #temp)
Declare #StaffName NVARCHAR(1024) = (SELECT TOP 1 FullName FROM #temp)
Declare #WorkingDays Int = (SELECT top 1 WorkingDays from #temp)
Declare #Leave INT = (SELECT top 1 [Absent] from #temp)
INSERT INTO ##SalarySheet(StaffID,FullName,[Absent]) values(#StaffID,#StaffName,#Leave)
DECLARE #HOPType INT
DECLARE #Value Decimal(19,7)
DECLARE #CalcVal DECIMAL(19,7) = 0
DECLARE #Formula NVARCHAR(MAX)
DECLARE #Total DECIMAL(19,7)
DECLARE #PayEvery INT
DECLARE #Round Int
Declare HOPList Cursor for SELECT ID,HOPType,Value,Formula,RoundOff,PayEvery FROM HRM.Tbl_HOP order by Schedule
open HOPList
FETCH NEXT FROM HOPList INTO #HopName,#HOPType,#Value,#Formula,#Round,#PayEvery
WHILE ##FETCH_STATUS = 0
BEGIN
if exists(select * from HRM.[Tbl_ContractHOPDetails] where PersonalDetailsID = #StaffID and HOPID = #HopName)
print('select * from HRM.[Tbl_ContractHOPDetails] where PersonalDetailsID = ' + convert(varchar(max), #StaffID) + ' and HOPID =' + convert(varchar(max),#HopName))
begin
if(#HOPType=51)
begin
exec HRM.Usp_GetSalaryValueFromFormula #StaffID,#Formula,#HOPType,#Leave,#WorkingDays,#Value output
set #HOPType= 50
end
if(#HOPType=50)
begin
set #CalcVal = #value
END
IF(#HOPType=38)
BEGIN
SET #CalcVal = #Value - ((#Value/#WorkingDays) * #Leave)
END
if(#PayEvery= 40)
begin
set #CalcVal = ((#CalcVal * #WorkingDays) - (#CalcVal * #Leave))
end
if(#Round = 45)
begin
set #CalcVal = round(#CalcVal,2)
end
else if(#Round = 46)
begin
set #CalcVal = CEILING(#CalcVal)
end
else if(#Round = 47)
begin
set #CalcVal = FLOOR(#CalcVal)
end
set #SMT ='UPDATE ##SalarySheet SET [' + #HopName + '] = ' + cast(#CalcVal as nvarchar(max)) + ' where StaffID = ' + cast(#StaffID as nvarchar(max))
exec (#smt)
end
SET #CalcVal = 0
FETCH NEXT FROM HOPList INTO #HopName,#HOPType,#Value,#Formula,#Round,#PayEvery
END
close HOPList
DEALLOCATE HOPList
set #SMT ='UPDATE ##SalarySheet SET [Total] = ' + cast(#Total as nvarchar(max)) + ' where StaffID = ' + cast(#StaffID as nvarchar(max))
exec (#smt)
Delete #temp Where StaffID = #TopID
end
select * from ##SalarySheet
drop table ##SalarySheet
This is my parent Stored Procudere and nested procedure is as follow:
CREATE proc [HRM].[Usp_GetSalaryValueFromFormula](#StaffID INT,#val nvarchar(max),#HOPType INT,#Leave INT,#WorkingDays INT, #GetResult Decimal(19,7) output)
as
set nocount on
Declare #Formula Varchar(max)
declare #initial INT =0
declare #final INT =0
Declare #DataVal NVARCHAR(MAX) -- set the value from HOP table
declare #FieldVal nvarchar(max)
declare #cnt int = 0
Declare #Complete Int =CHARINDEX ('[',#val,0)
while (#Complete <> 0)
begin
set #initial = CHARINDEX ('[',#val,0)
set #final = CHARINDEX(']',#val,0)
set #FieldVal = SUBSTRING(#val,#initial,(#final-#initial) + 1)
if len(#FieldVal)<>0
begin
select #HOPType = HOPType, #DataVal= ( case when HOPType = 51 then [Formula] else cast([Value] as nvarchar(max)) end) from HRM.Tbl_ContractHOPDetails where PersonalDetailsID = #StaffID and HOPID in(select ID from HRM.tbl_HOP where HOPName = replace(replace(#fieldVal,'[',''),']',''))
if (#DataVal is null or #DataVal ='')
begin
RAISERROR ('Nested HOP is not defined.',11,1)
RETURN
end
print(#DataVal)
if ISNUMERIC(#DataVal)=1
begin
if(#HOPType = 38)
begin
SET #DataVal = cast(#DataVal as decimal(19,7)) - ((cast(#DataVal as decimal(19,7))/#WorkingDays) * #Leave)
end
end
set #val = replace(#val,#fieldVal,#DataVal)
set #fieldVal= ''
set #DataVal = ''
end
set #Complete = CHARINDEX ('[',#val,0)
set #fieldVal =''
set #final =0
set #initial = 0
end
SET #Complete =CHARINDEX ('{',#val,0)
while (#Complete <> 0)
BEGIN
set #initial = CHARINDEX ('{',#val,0)
set #final = CHARINDEX('}',#val,0)
set #FieldVal = SUBSTRING(#val,#initial+1,(#final-#initial)-1)
if len(#FieldVal)<>0
begin
set #DataVal = isnumeric((SELECT 0 FROM [HRM].Tbl_StaffTag where CValue = #FieldVal and StaffID = #StaffID))
set #FieldVal = '{' + #FieldVal + '}'
set #val = replace(#val,#fieldVal,#DataVal)
set #fieldVal= ''
set #DataVal = ''
end
set #Complete = CHARINDEX ('{',#val,0)
set #final =0
set #initial = 0
END
DECLARE #RetrunVal DECIMAL(19,7)
declare #ParmDefinition Nvarchar(512) = '#GetVal decimal(19,7) OUTPUT'
Declare #SMT NVARCHAR(MAX) = ' SET #GetVal = ' + #val
EXECUTE sp_executeSQL #Smt, #ParmDefinition, #GetVal =#RetrunVal OUTPUT
set #GetResult = #RetrunVal
But in current situation it raises error and again from the main procedure it runs next step of loop. But I want to terminate the complete process after this raiserror
Kindly help me
My guess is that RaiseError throws the control back to the caller, which might make the Return statement unreachable. The caller (loop) continues with next iteration.
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'
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 ;
I found the following stored procedure from here, while creating this stored procedure in my database, I get this error message: (I'm running SQL Server 2008 Developer)
Msg 102, Level 15, State 1, Procedure HighLightSearch, Line 23
Incorrect syntax near '+'.
Here is the full Stored Procedure code:
CREATE FUNCTION [dbo].[HighLightSearch](#contents NVARCHAR(MAX), #searchTerm NVARCHAR(4000), #style NVARCHAR(4000), #maxLen INT)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #c NCHAR(1)
DECLARE #len INT = 0
DECLARE #l INT = 0
DECLARE #p INT = 0
DECLARE #prevPos INT = 0
DECLARE #margin INT
DECLARE #term NVARCHAR(4000)
DECLARE #retval NVARCHAR(MAX) = ''
DECLARE #positions TABLE
(
S INT,
L INT
)
-- find all occurances of the search term
DECLARE cur1 CURSOR FOR
SELECT display_term FROM sys.dm_fts_parser(N'FORMSOF(FREETEXT, "' + #searchTerm + '")', 1033, 0, 1)
OPEN cur1
FETCH NEXT FROM cur1 INTO #term
WHILE ##FETCH_STATUS = 0
BEGIN
WHILE 1 = 1
BEGIN
SET #p = CHARINDEX(#term, #contents, #p)
IF #p <= 0 BREAK
SET #l = LEN(#term)
IF #p > 0 BEGIN
SET #c = SUBSTRING(#contents, #p - 1, 1)
IF #c <> ' ' AND #c <> NCHAR(9) AND #c <> NCHAR(13) AND #c <> NCHAR(10) BREAK
END
INSERT INTO #positions (S, L) VALUES(#p, #l)
SET #p = #p + LEN(#term)
END
FETCH NEXT FROM cur1 INTO #term
END
CLOSE cur1
DEALLOCATE cur1
-- build the result string
DECLARE cur2 CURSOR FOR
SELECT S, MAX(L)
FROM #positions
GROUP BY S
ORDER BY S
SET #margin = LOG(#maxLen) * 5
IF #margin > #maxLen / 4 SET #margin = #maxLen / 4
SELECT #prevPos = MIN(S) - #margin FROM #positions
OPEN cur2
FETCH NEXT FROM cur2 INTO #p, #l
WHILE ##FETCH_STATUS = 0 AND #len < #maxLen
BEGIN
SET #retval = #retval + SUBSTRING(#contents, #prevPos, #p - #prevPos)
SET #retval = #retval + '<span style="' + #style + '">' + SUBSTRING(#contents, #p, #l) + '</span>'
SET #len = #len + #p - #prevPos + #l
SET #prevPos = #p + #l
FETCH NEXT FROM cur2 INTO #p, #l
END
CLOSE cur2
DEALLOCATE cur2
SET #margin = LOG(#maxLen) * 5
IF #margin + #len < #maxLen SET #margin = #maxLen - #len
IF #margin > 0 SET #retval = #retval + SUBSTRING(#contents, #prevPos, #l)
RETURN '...' + #retval + '...'
END
Try doing
DECLARE #var NVARCHAR(4000)
SET #var=N'FORMSOF(FREETEXT, "' + #searchTerm + '")'
DECLARE cur1 CURSOR FOR
SELECT display_term FROM sys.dm_fts_parser(#var, 1033, 0, 1)