newbie here.
I am trying to do self-learning about SQL.
Right now, I am having a problem in combining procedure and cursor.
Hereby the case
The Case
Create procedure named ‘sp4’ that receive StaffName from user’s input
to display StaffName and StaffPosition for every staff which name
contains the word that has been inputted by user.
(create procedure, declare cursor, like)
Hereby the code that I have tried it
My Code
CREATE PROCEDURE sp4 (#name VARCHAR(100))
AS
DECLARE cur2 CURSOR
SCROLL
FOR
SELECT StaffName, StaffPosition
FROM MsStaff
OPEN cur2
DECLARE #pointer AS VARCHAR(100)
FETCH NEXT FROM cur2 INTO #pointer
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT StaffName, StaffPosition
FROM MsStaff
WHERE #pointer = #name
AND StaffName LIKE '%' + #pointer + '%'
FETCH NEXT FROM cur2 INTO #name
END
CLOSE cur2
DEALLOCATE cur2
Your SELECT statement for the cursor indicates SELECT StaffName, StaffPosition but your FETCH statements don't match that (or each other).
The FETCH is going to load the data from the cursor into your memory variables. So you need to supply one variable for each column indicated in the SELECT. For example, if you have
DECLARE #staffName VARCHAR(100)
DECLARE #staffPosition VARCHAR(100)
then you can replace both of your fetches with:
FETCH NEXT FROM cur2 INTO #staffName, #staffPosition
Related
I want to use a database cursor; first I need to understand what its use and syntax are, and in which scenario we can use this in stored procedures? Are there different syntaxes for different versions of SQL Server?
When is it necessary to use?
Cursors are a mechanism to explicitly enumerate through the rows of a result set, rather than retrieving it as such.
However, while they may be more comfortable to use for programmers accustomed to writing While Not RS.EOF Do ..., they are typically a thing to be avoided within SQL Server stored procedures if at all possible -- if you can write a query without the use of cursors, you give the optimizer a much better chance to find a fast way to implement it.
In all honesty, I've never found a realistic use case for a cursor that couldn't be avoided, with the exception of a few administrative tasks such as looping over all indexes in the catalog and rebuilding them. I suppose they might have some uses in report generation or mail merges, but it's probably more efficient to do the cursor-like work in an application that talks to the database, letting the database engine do what it does best -- set manipulation.
cursor are used because in sub query we can fetch record row by row
so we use cursor to fetch records
Example of cursor:
DECLARE #eName varchar(50), #job varchar(50)
DECLARE MynewCursor CURSOR -- Declare cursor name
FOR
Select eName, job FROM emp where deptno =10
OPEN MynewCursor -- open the cursor
FETCH NEXT FROM MynewCursor
INTO #eName, #job
PRINT #eName + ' ' + #job -- print the name
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM MynewCursor
INTO #ename, #job
PRINT #eName +' ' + #job -- print the name
END
CLOSE MynewCursor
DEALLOCATE MynewCursor
OUTPUT:
ROHIT PRG
jayesh PRG
Rocky prg
Rocky prg
Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop).
To use cursors in SQL procedures, you need to do the following:
1.Declare a cursor that defines a result set.
2.Open the cursor to establish the result set.
3.Fetch the data into local variables as needed from the cursor, one row at a time.
4.Close the cursor when done.
for ex:
declare #tab table
(
Game varchar(15),
Rollno varchar(15)
)
insert into #tab values('Cricket','R11')
insert into #tab values('VollyBall','R12')
declare #game varchar(20)
declare #Rollno varchar(20)
declare cur2 cursor for select game,rollno from #tab
open cur2
fetch next from cur2 into #game,#rollno
WHILE ##FETCH_STATUS = 0
begin
print #game
print #rollno
FETCH NEXT FROM cur2 into #game,#rollno
end
close cur2
deallocate cur2
Cursor itself is an iterator (like WHILE). By saying iterator I mean a way to traverse the record set (aka a set of selected data rows) and do operations on it while traversing. Operations could be INSERT or DELETE for example. Hence you can use it for data retrieval for example. Cursor works with the rows of the result set sequentially - row by row. A cursor can be viewed as a pointer to one row in a set of rows and can only reference one row at a time, but can move to other rows of the result set as needed.
This link can has a clear explanation of its syntax and contains additional information plus examples.
Cursors can be used in Sprocs too. They are a shortcut that allow you to use one query to do a task instead of several queries. However, cursors recognize scope and are considered undefined out of the scope of the sproc and their operations execute within a single procedure. A stored procedure cannot open, fetch, or close a cursor that was not declared in the procedure.
I would argue you might want to use a cursor when you want to do comparisons of characteristics that are on different rows of the return set, or if you want to write a different output row format than a standard one in certain cases. Two examples come to mind:
One was in a college where each add and drop of a class had its own row in the table. It might have been bad design but you needed to compare across rows to know how many add and drop rows you had in order to determine whether the person was in the class or not. I can't think of a straight forward way to do that with only sql.
Another example is writing a journal total line for GL journals. You get an arbitrary number of debits and credits in your journal, you have many journals in your rowset return, and you want to write a journal total line every time you finish a journal to post it into a General Ledger. With a cursor you could tell when you left one journal and started another and have accumulators for your debits and credits and write a journal total line (or table insert) that was different than the debit/credit line.
CREATE PROCEDURE [dbo].[SP_Data_newUsingCursor]
(
#SCode NVARCHAR(MAX)=NULL,
#Month INT=NULL,
#Year INT=NULL,
#Msg NVARCHAR(MAX)=null OUTPUT
)
AS
BEGIN
DECLARE #SEPERATOR as VARCHAR(1)
DECLARE #SP INT
DECLARE #VALUE VARCHAR(MAX)
SET #SEPERATOR = ','
CREATE TABLE #TempSiteCode (id int NOT NULL)
WHILE PATINDEX('%' + #SEPERATOR + '%', #SCode ) <> 0
BEGIN
SELECT #SP = PATINDEX('%' + #SEPERATOR + '%' ,#SCode)
SELECT #VALUE = LEFT(#SCode , #SP - 1)
SELECT #SCode = STUFF(#SCode, 1, #SP, '')
INSERT INTO #TempSiteCode (id) VALUES (#VALUE)
END
DECLARE
#EmpCode bigint=null,
#EmpName nvarchar(50)=null
CREATE TABLE #TempEmpDetail
(
EmpCode bigint
)
CREATE TABLE #TempFinalDetail
(
EmpCode bigint,
EmpName nvarchar(500)
)
DECLARE #TempSCursor CURSOR
DECLARE #TempFinalCursor CURSOR
INSERT INTO #TempEmpDetail
(
EmpCode
)
(
SELECT DISTINCT EmpCode FRom tbl_Att_MSCode
WHERE tbl_Att_MSCode.SiteCode IN (SELECT id FROM #TempSiteCode)
AND fldMonth=#Month AND fldYear=#Year
)
SET #TempSiteFinalCursor=CURSOR FOR SELECT EmpCode FROM #TempEmpDetail
OPEN #TempSiteFinalCursor
FETCH NEXT FROM #TempSiteFinalCursor INTO #EmpCode,#SiteCode,#HrdCompanyId
WHILE ##FETCH_STATUS=0
BEGIN
SEt #EmpName=(SELECt EmpName FROm tbl_Employees WHERE EmpCode=#EmpCode)
INSERT INTO #TempFinalDetail
(
EmpCode,
EmpName
)
VALUES
(
#EmpCode,
#EmpName
)
FETCH NEXT FROM #TempSiteFinalCursor INTO #EmpCode
END
SELECT EmpCode,
EmpName
FROM #TempFinalDetail
DEALLOCATE #TempSiteFinalCursor
DROP TABLE #TempEmpDetail
DROP TABLE #TempFinalDetail
END
I want to create an array in sql with user ids, and create a loop which will pick user id from array. And create a user in sql db.
Please find the code below. It is not working as expected :
declare type namesarray IS VARARRAY (50) OF VARCHAR2 (10);
declare name namesarray;
declare total integer;
names = namesarray('resh1','resh2');
total = names.count;
while (i <= total)
begin
EXECUTE IMMEDIATE 'create user names(i) identified by newpass01;
dbms_output.put_line("created user 'names(i)");
end
dbms_output.put_line("cannot create user 'names(i)");
In Sql Server , it is done as below. You can use table variable.
Declare #namesarray table
(name varchar(50));
Declare #Name varchar(50);
Insert #namesarray values ('resh1');
Insert #namesarray values ('resh2');
Declare name_cur CURSOR FOR
Select name from #namesarray ;
OPEN name_cur
FETCH NEXT FROM name_cur INTO #Name
WHILE ##FETCH_STATUS = 0
BEGIN
Print #Name
FETCH NEXT FROM name_cur INTO #Name
END
CLOSE name_cur
DEALLOCATE name_cur
when I try to use my udf i get an error saying:
Conversion failed when converting the varchar value 'Mar A' to data type int.
I use northwind database and here's my code:
alter function test_fu (#city varchar(70))
returns varchar(70)
as
begin
declare #name varchar(70)
declare kursor cursor
for (select [ContactName]
from Contacts
where City = #city)
open kursor
fetch next from kursor into #name
set #name=#name+1
while ##FETCH_STATUS=0
close kursor
Deallocate kursor
return #name
end
First of all, your cursor has logical errors, move the while ##FETCH_STATUS=0 right after the cursor opening, then execute something and move it to next value
begin
print 'your current selected name is: '+#name
fetch next from kursor into #name
end
Check the edits:
use AdventureWorks2017
declare #name varchar(70)
declare kursor cursor
for (
select firstname
from Person.Person
where Person.Title = 'Mr.'
)
open kursor
fetch next from kursor into #name
while ##FETCH_STATUS=0
begin
print 'your current selected name is: '+#name
-- your statement goes here
fetch next from kursor into #name
end
close kursor
Deallocate kursor
But anyway i agree with Gordon's answer: there are several other ways (better ways actually) to avoid using cursor in described situation
Why would you use a cursor for this?
alter function test_fu (#city varchar(70))
returns varchar(70)
as
begin
declare #name varchar(70)
select top (1) #name = ContactName
from Contacts
where City = #city;
return #name;
end;
This structure brings up a fundamental question about the data structure: Does each city really have only one contact? If not, which one do you want? I suspect that this function is not really doing anything particularly useful, even if it were working.
Using SQL Server 2016, I have a huge query for our Finance Dept that uses #Year and #FinPeriod to match up transactions with a period. And for reporting we normally pass a single value into the stored procedure. But now we are required to populate the underlying tables with the data that would normally be generated on the fly.
Is there a loop anyone can help with please? I have a temp table with year values column and a finperiod for each of those years. I am looking to loop through this table - passing in both year and period to the stored procedure, one after the other until they have all been ran.
The stored procedure element is fine for me, just getting the loop/passing part to work would be a help.
So far I have:
declare #fiscalyearid numeric(9)
declare #FiscalYear numeric(9)
declare #FiscalMonthOfYear numeric(9)
declare #Year numeric(9)
declare #FinPeriod numeric(9)
if object_id('tempdb..#dateloop','u') is not null
drop table #dateloop
select distinct
identity(int,1,1) as ID,
FiscalYear_int, FiscalMonthOfYear
into
#dateloop
from
[DW].[DDS].[dimDate]
where
FiscalYear_int = '2018'
DECLARE C CURSOR LOCAL FAST_FORWARD FOR --
SELECT
ID, FiscalYear_int, FiscalMonthOfYear
FROM
#dateloop;
OPEN C;
FETCH C INTO #FiscalYear, #FiscalMonthOfYear;
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC [dbo].[Origen_Reporting->SSRS_Capex_Monitoring_Report_Expenditure] #Year, #FinPeriod
FETCH C INTO #Year,#FinPeriod
END
CLOSE C;
DEALLOCATE C;
Any tips would be brilliant. Thank you
I guess you want your Cursor logic to work. Below is the code you can use to loop through your dates and call proc in loop.
DECLARE C CURSOR LOCAL FAST_FORWARD FOR --
SELECT
FiscalYear_int, FiscalMonthOfYear
FROM
#dateloop;
OPEN C;
Fetch next from c into #FiscalYear, #FiscalMonthOfYear
WHILE ##FETCH_STATUS = 0
BEGIN
select #FiscalYear, #FiscalMonthOfYear --exec proc passing these values
EXEC [dbo].[Origen_Reporting->SSRS_Capex_Monitoring_Report_Expenditure] #FiscalYear, #FiscalMonthOfYear
FETCH next from c INTO #FiscalYear,#FiscalMonthOfYear
END
CLOSE C;
DEALLOCATE C;
Is it possible to use a table as input for a stored procedure?
EXEC sp_Proc SELECT * FROM myTable
I've created a function to return a table consisting of a single record.
ALTER FUNCTION dbo.preEmail
(
#Num INT,
#WID INT
)
RETURNS
#Results TABLE
(
WID char(10),
Company nchar(50),
Tech nchar(25),
StartDate datetime,
Description varchar(max),
Address varchar(200),
Phone varchar(15),
Status varchar(35)
)
AS
BEGIN
INSERT INTO #Results
(WID, Company, Tech, StartDate, Description, Address, Phone, Status)
SELECT WID, company, tech, startDate, description, address, phone, status
FROM wo_tbl
WHERE Num = #Number AND wid = #WID
RETURN
END
GO
Next I have a stored procedure that sends an email to the tech that is scheduled in the above record.
EXEC sp_emailTech #WID, #Company, #Tech, #StartDate, #Description, #Address, #Phone, #Status.
but I'd rather do
EXEC sp_emailTech SELECT * FROM dbo.preEmail(1, 5746)
No, you cannot pass a table as a parameter like that.
You could however look at using a Use Table-Valued Parameters (Database Engine) (SQL Server 2008 up)
In your case however it seems that you might be looking at using a DECLARE CURSOR (Transact-SQL) rather.
Do be aware thought that cursor execution does have a performance hit over set-based queries.
Re #Aaron Bertrand comment
DECLARE #id INT,
#name varchar(5)
DECLARE Cur CURSOR FOR
SELECT *
FROM myTable
OPEN Cur
FETCH NEXT FROM Cur INTO #ID, #Name
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC sp_Proc #id, #Name
FETCH NEXT FROM Cur INTO #ID, #Name
END
CLOSE Cur
DEALLOCATE Cur
First, declare a table variable to hold the result. Then, execute the SP with the rigth parameters and hold the result in the previous declared table variable. Then, select the content of this table.
You should also give a look to this solved SO thread. Also, I would recommend you to have a look at OPENXML query (pass in table xml and using xpath access the respective field).
See these examples:
Example 1
Example 2