Incorrect Syntax Near Cursor - sql-server

I have written the below code and it throws an error as 'Incorrect Syntax near mycursor'. Can anyone let me know what am I doing wrong?
SELECT DISTINCT [FILE_NAME] INTO #TEMP FROM [dbo].[ABI_IND_STR_PLAN_DAILY] WHERE Year<>'Year';
DECLARE #var CHAR(20)
DECLARE #str VARCHAR(1000)
DECLARE myCursor CURSOR
FOR SELECT distinct [FILE_NAME] FROM #TEMP
--SET #str=''
OPEN myCursor
--'''+#var+''',
FETCH NEXT FROM myCursor INTO #var
WHILE ##FETCH_STATUS=0
BEGIN
SET #str=' INSERT INTO [dbo].[ABI_IND_STR_PLAN_DAILY] SELECT
* from [dbo].[ABI_IND_STR_PLAN_DAILY] WHERE FILE_NAME='+#var ---------------- Change GL Period Accordingly , for eg if it is JUN YTD then GL period '<=6' if only JUN MTD then GL Period = 6
FETCH NEXT FROM myCursor INTO #var
PRINT(#str)
EXEC(#str)
END
CLOSE myCursor
DEALLOCATE myCursor

Related

SQL SERVER query cursor with dynamic LinkedServer

I want to monitor few SQL SERVER instances (about 31), and I want to prepare a procedure that will aggregate data from instances based on sys.servers list, but I cant dynamically ask a server.
DECLARE #instance_name sysname;
DECLARE instance_cursor CURSOR FOR
select data_source from sys.servers where is_linked = 1;
OPEN instance_cursor
FETCH NEXT FROM instance_cursor INTO #instance_name
WHILE ##FETCH_STATUS = 0
BEGIN
--Do something on a linked server
SELECT 1 FROM #instance_name.master.sys.master_files
FETCH NEXT FROM instance_cursor INTO #instance_name
END
CLOSE instance_cursor
DEALLOCATE instance_cursor
USE master
GO
IF OBJECT_ID('tempdb..#server_info') IS NOT NULL
DROP TABLE #server_info
CREATE TABLE #server_info
(
Col1 SQL_VARIANT,
Col2 SQL_VARIANT,
Col3 SQL_VARIANT,
Col4 SQL_VARIANT
) -- change data type as needed.
DECLARE #instance_name NVARCHAR(255);
DECLARE #sql NVARCHAR(MAX)
DECLARE instance_cursor CURSOR FOR
SELECT name FROM master.sys.servers WHERE is_linked = 1
ORDER BY name
OPEN instance_cursor
FETCH NEXT FROM instance_cursor INTO #instance_name
WHILE ##FETCH_STATUS = 0
BEGIN
--Do something on a linked server
SET #sql = 'INSERT INTO #server_info (Col1,Col2,Col3,Col4) SELECT .... FROM ' + #instance_name + '.master.sys...'
PRINT #sql -- verify for your syntax
EXEC (#sql)
FETCH NEXT FROM instance_cursor INTO #instance_name
END
CLOSE instance_cursor
DEALLOCATE instance_cursor
SELECT * FROM #server_info
I'm not found a perfect solution for this, but:
CREATE PROCEDURE [kk].[query_ls]
#SQL NVARCHAR(MAX)
AS
BEGIN
DECLARE #query NVARCHAR(MAX);
DECLARE #instance_name sysname;
DECLARE instance_cursor CURSOR FOR
select data_source from sys.servers where is_linked = 1;
OPEN instance_cursor
FETCH NEXT FROM instance_cursor INTO #instance_name
WHILE ##FETCH_STATUS = 0
BEGIN
SET #query = REPLACE(#SQL,'#server#',#instance_name )
EXEC (#query)
FETCH NEXT FROM instance_cursor INTO #instance_name
END
CLOSE instance_cursor
DEALLOCATE instance_cursor
END
And usage example:
EXEC [kk].[query_ls] N'use _dba INSERT INTO kk.cpuUsagePerDB select *,getdate() from [#server#]._dba.kk.[V_cpuUsagePerDB]'
Another solution can be achieved by OPENQUERY

Transact sql : must declare the scalar variable

I'm trying to iterate over some tables and clear all records.
My code is the following :
DECLARE #table varchar(100)
DECLARE db_cursor CURSOR FOR select name from sys.tables where name like '%cfe_%'
OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO #table
WHILE ##FETCH_STATUS = 0  
BEGIN  
print #table
delete from #table
       FETCH NEXT FROM db_cursor INTO #table  
END  
CLOSE db_cursor  
DEALLOCATE db_cursor
But I receive "Must declare the table variable "#table" at the line "delete..."
I can't see the error.
Thank you
You shoud use dynamic query,
DECLARE #table varchar(100)
,#v_str nvarchar(200)
DECLARE db_cursor CURSOR FOR select name from sys.tables where name like '%cfe_%'
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #table
WHILE ##FETCH_STATUS = 0
BEGIN
print #table
set #v_str = 'delete from '+#table
exec(#v_str)
FETCH NEXT FROM db_cursor INTO #table
END
CLOSE db_cursor
DEALLOCATE db_cursor
You need dynamic delete statement... Try this :
DECLARE #cmd VARCHAR(4000)
DECLARE #table varchar(100)
DECLARE db_cursor CURSOR FOR select name from sys.tables where name like '%cfe_%'
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #table
WHILE ##FETCH_STATUS = 0
BEGIN
SET #cmd = 'DELETE FROM '+#table
EXEC (#cmd)
FETCH NEXT FROM db_cursor INTO #table
END
CLOSE db_cursor
DEALLOCATE db_cursor
Even better would be to not use a cursor here. Looping in sql is a last resort. Also, your query is not going to do exactly what you think it will because you are using like and wanting to find an underscore. The underscore in a LIKE predicate requires it to be escaped with square brackets. As posted your query will return any table with cfe in the name not cfe_.
Once you are comfortable that the dynamic sql string is what you want you can uncomment it to execute it.
declare #SQL nvarchar(max) = ''
select #SQL = #SQL + 'delete from ' + name + ';'
from sys.tables
where name like '%cfe[_]%'
select #SQL
--exec sp_executesql #SQL
We can also use while loop for this process
DECLARE #Min Int,#max Int
IF Object_id('Tempdb..#DeleteList')IS NOT NULL
DROP TABLE #DeleteList
CREATE TABLE #DeleteList (Id Int Identity,Name varchar(100))
INSERT INTO #DeleteList(Name)
SELECT name FROM sys.tables WHERE CHARINDEX('cfe_',name)>0
SELECT #Min=Min(Id) FROm #DeleteList
SELECT #max=MAX(Id) FROm #DeleteList
While(#Min<=#max)
Begin
Declare #TableName Varchar(50),
#Sql Nvarchar(max)
SELECT #TableName=Name From #DeleteList Where id=#Min
SET #Sql='DELETE From '+#TableName
Exec (#Sql)
SET #Min=#Min+1
END
But if the deleting tables have foreign key refrences it will throw error so that first you need delete records from child and then go to Parent table
You will need to do something like;
EXEC sp_executesql #statement = N'DELETE FROM ' + #table
because currently you are trying to delete from a String variable, not the table named the same as the variable

How to use parameter variables in Cursor SQL

I am writing a Scalar function for my web application. I want to calculate the date difference between an employee's Join Date and Resign Date.
I have got most of my code working, but I just cannot figure out how to use parameter variables in cursor.
Let say I have this block of code
Declare myCursor Cursor for
Declare #join_date datetime
Declare #resign_date datetime
Declare #emp_stat nvarchar(50)
--What I have been trying to do. (Not working)
Select #join_date = Convert(datetime, join_date), #emp_stat = Convert(datetime, emp_stat) from t_emp_info where .....
OPEN product_cursor
WHILE ##FETCH_STATUS = 0
BEGIN
if (#emp_stat = 'P')
Begin
//DateDiff .....
End
FETCH NEXT FROM vendor_cursor
INTO #join_date , #emp_stat
End
Close myCursor
DEALLOCATE myCursor;
I can't get this working, but what I want is I want to store the values in the parameter so I can use it in the if condition statement. Not sure how to fix this. Help will be appreciated
Your cursor names are mixed up and your assignment is in the wrong place. Try:
Declare myCursor Cursor for
Select join_date, emp_stat, resign_date from t_emp_info where .....
Declare #join_date datetime
Declare #resign_date datetime
Declare #emp_stat nvarchar(50)
OPEN myCursor
FETCH NEXT FROM myCursor
INTO #join_date , #emp_stat , #resign_date
WHILE ##FETCH_STATUS = 0
BEGIN
//Your logic here
FETCH NEXT FROM myCursor
INTO #join_date , #emp_stat, #resign_date
End
Close myCursor
DEALLOCATE myCursor;
However you should avoid the cursor. What is wrong with:
SELECT DATEDIFF(day, MAX(join_date), case when emp_stat = 'P' then getdate() else MAX(resign_date) end)
from t_emp_info
GROUP BY employee_id
Or similar?

Invalid cursor state

We have triggers on a table called OSPP to save specific data to a table for later use.
I get the following error in SAP when adding more than one line at a time to the table.
Invalid Cursor State
We have SQL Server 2005 SP3 (but I tried it on a clean 2005 install, on SP1 and SP2)
The one trigger :
CREATE TRIGGER [dbo].[tr_OSPP_Insert]
ON [dbo].[OSPP]
FOR INSERT
AS
BEGIN
Declare #ItemCode varchar(255)
Declare #CardCode varchar(255)
Declare #Price decimal(18,2)
Declare #ListNum bigint
Declare #ID bigint
Declare #Remote char(1)
DECLARE db_cursor CURSOR FOR
SELECT ItemCode, CardCode, Price, ListNum
FROM INSERTED
OPEN db_cursor
FETCH NEXT
FROM db_cursor INTO #ItemCode, #CardCode, #Price, #ListNum
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #Remote = isnull(U_Remote, 'N') FROM OITM WHERE ItemCode = #ItemCode
IF ltrim(rtrim(upper(#Remote))) = 'Y'
BEGIN
SELECT #ID = U_ID FROM [dbo].[#BDS_MAINTENANCE]
UPDATE [dbo].[#BDS_MAINTENANCE] set U_ID = U_ID + 1
INSERT INTO [dbo].[#BDS_REMOTESPECIALPRICELIST]
(
Code,
[Name],
U_ID,
U_ItemCode,
U_CardCode,
U_Price,
U_ListNum,
U_TransactionType,
U_Uploaded
) VALUES (
#ID,
'_' + cast(#ID as VARCHAR(50)),
#ID,
#ItemCode,
#CardCode,
#Price,
#ListNum,
1,
0
)
FETCH NEXT
FROM db_cursor INTO #ItemCode, #CardCode, #Price, #ListNum
END
CLOSE db_cursor
DEALLOCATE db_cursor
END
END
We also tried :
CREATE TRIGGER [dbo].[tr_OSPP_Insert]
ON [dbo].[OSPP]
FOR INSERT
AS
BEGIN
SELECT * INTO [#TEMPTABLE222] FROM INSERTED
END
But still get the same error.
Do you guys have any idea what is wrong?
Thanks in advance!
I count three Begins, and three Ends. But it's the second pair that represent the cursor loop - so I'd move your Close/Deallocate to be after the second End, rather than before. E.g:
FETCH NEXT
FROM db_cursor INTO #ItemCode, #CardCode, #Price, #ListNum
END
CLOSE db_cursor
DEALLOCATE db_cursor
END
Probably needs to be:
END
FETCH NEXT
FROM db_cursor INTO #ItemCode, #CardCode, #Price, #ListNum
END
CLOSE db_cursor
DEALLOCATE db_cursor
(I've also moved the fetch next one level out, since otherwise you only move the cursor forwards inside your IF condition)
And one style comment (can't resist). It's generally considered good practice to SET NOCOUNT ON within the body of a trigger, to avoid sending lots of extra n rows affected messages.

solving a problem with cursors

I have a question. I am working on cursors. Each time, after fetching the last records and printing its data’s, the cursor prints an addition line. To understand what I mean please consider the following sample example:
I want to print the information about only 10 customers.
USE Northwind
GO
DECLARE myCursor CURSOR
FOR SELECT TOP(10) ContactName FROM Customers
DECLARE #RowNo int,#ContactName nvarchar(30)
SET #RowNo=1
OPEN myCursor
FETCH NEXT FROM myCursor INTO #ContactName
PRINT LEFT(CAST(#rowNo as varchar) + ' ',6)+' '+ #ContactName
SET #RowNo=#RowNo+1
SET #ContactName=''
WHILE ##FETCH_STATUS=0
BEGIN
FETCH NEXT FROM myCursor INTO #ContactName
PRINT + LEFT(CAST(#rowNo as varchar) + ' ',6)+' '+ #ContactName
SET #RowNo=#RowNo+1
SET #ContactName=''
END
CLOSE myCursor
DEALLOCATE myCursor
Now look at the output:
1 Maria Anders
2 Ana Trujillo
3 Antonio Moreno
4 Thomas Hardy
5 Christina Berglund
6 Hanna Moos
7 Frédérique Citeaux
8 Martín Sommer
9 Laurence Lebihan
10 Elizabeth Lincoln
11
The row number 11 also has been printed. Is it a problem in a cursor or it always occurs?
Is there any way not to print this addition data? Thanks
(i use sql erver 2008)
Either...
FETCH NEXT FROM myCursor INTO #ContactName
WHILE ##FETCH_STATUS = 0
BEGIN
-- do stuff
FETCH NEXT FROM myCursor INTO #ContactName
END
Or...
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM myCursor INTO #ContactName
IF ##FETCH_STATUS = 0
BEGIN
-- do stuff
END
END
Or...
WHILE (1 = 1)
BEGIN
FETCH NEXT FROM myCursor INTO #ContactName
IF ##FETCH_STATUS <> 0
BREAK
-- do stuff
END
You mentioned you're using SQL Server 2008. With SQL Server 2005 or greater, you don't need a cursor at all to do what you want.
select top 10 left(cast(row_number() over(order by ContactName) as varchar)+ ' ', 6) + ContactName
from Customers
See how you have the printing logic duplicated? That's a pointer to what's going wrong. Your loop should look like this:
FETCH NEXT INTO #working_variables
WHILE ##FETCH_STATUS = 0
-- process #working_variables
FETCH NEXT INTO #working_variables
The only duplicated code should be the FETCH NEXT itself - the way you have it now, the last FETCH happens, but you PRINT a line before the WHILE can exit.
A FETCH at the end of the record set sets ##FETCH_STATUS to not 0.
The FETCH NEXT command should be the last line in the WHILE BLOCK.
USE Northwind
GO
DECLARE myCursor CURSOR
FOR SELECT TOP(10) ContactName FROM Customers
DECLARE #RowNo int,#ContactName nvarchar(30)
SET #RowNo=0
OPEN myCursor
FETCH NEXT FROM myCursor INTO #ContactName
WHILE ##FETCH_STATUS=0
BEGIN
SET #RowNo=#RowNo+1
SET #ContactName=''
PRINT + LEFT(CAST(#rowNo as varchar) + ' ',6)+' '+ #ContactName
FETCH NEXT FROM myCursor INTO #ContactName
END
CLOSE myCursor
DEALLOCATE myCursor
This is an off-by-one error. Here's a better way to iterate through a cursor, w/ less code duplication:
USE Northwind
GO
DECLARE myCursor CURSOR
FOR SELECT TOP(10) ContactName FROM Customers
DECLARE #RowNo int,#ContactName nvarchar(30)
SET #RowNo=0 -- initialize counters at zero, increment after the fetch/break
OPEN myCursor
WHILE 1=1 BEGIN -- start an infinite loop
FETCH NEXT FROM myCursor INTO #ContactName
IF ##FETCH_STATUS <> 0 BREAK
SET #RowNo=#RowNo+1
PRINT LEFT(CAST(#rowNo as varchar) + ' ',6)+' '+ #ContactName
END
CLOSE myCursor
DEALLOCATE myCursor
For extra points, use a cursor variable and declare w/ FAST_FORWARD and TYPE_WARNING, or STATIC for small datasets. eg:
DECLARE #cursor CURSOR
SET #cursor = CURSOR FAST_FORWARD TYPE_WARNING FOR
SELECT TOP (10) ContactName FROM Customers
OPEN #cursor
......
CLOSE #cursor
DEALLOCATE #cursor
CLOSE and DEALLOCATE are not strictly necessary, as the cursor variable will go out of scope at the end of the batch. It is still good form, however, as you might add more code at the end later on, and you should free up resources as early as possible.
TYPE_WARNING tells you when SQL Server implicitly converts the requested cursor type (FAST_FORWARD) to another type (typically STATIC), if the requested type is incompatible w/ your SELECT statement.

Resources