My task is to make it impossible to add a row that contains wrong form of certain attribute called pesel. Firstly I thought I should write a trigger and it worked fine but I was told to change it to cursor because when user want to add many values at once insert will stop at first wrong pesel and it won't check the others. So far I came up with this but it seems like it never ends after I execute it.
DECLARE cursor_pesel CURSOR FOR
SELECT pesel FROM person;
DECLARE #pesel CHAR(11)
DECLARE #WEIGHTS as table (position INT IDENTITY(1,1), weight TINYINT)
INSERT INTO #WEIGHTS
VALUES (1), (3), (7), (9), (1), (3), (7), (9), (1), (3), (1)
OPEN cursor_pesel
FETCH NEXT FROM cursor_pesel INTO #pesel
WHILE ##FETCH_STATUS = 0
BEGIN
IF (LEN(#pesel) != 11 OR (ISNUMERIC(#pesel) = 0))
RAISERROR('BAD FORM OF PESEL',1,1)
IF (SELECT SUM(CONVERT(INT, SUBSTRING(#pesel, position,1)) * weight) % 10
FROM #WEIGHTS) != 0
RAISERROR('BAD FORM OF PESEL',1,1)
END
CLOSE cursor_pesel
You forgot to fetch next records:
FETCH NEXT FROM cursor_pesel INTO #pesel
DECLARE cursor_pesel CURSOR
FOR SELECT pesel FROM person;
DECLARE #pesel CHAR(11)
DECLARE #WEIGHTS as table (position INT IDENTITY(1,1), weight TINYINT)
INSERT INTO #WEIGHTS VALUES (1),(3),(7),(9),(1),(3),(7),(9),(1),(3),(1)
OPEN cursor_pesel
FETCH NEXT FROM cursor_pesel INTO #pesel
WHILE ##FETCH_STATUS=0
BEGIN
IF (LEN(#pesel)!=11 OR (ISNUMERIC(#pesel)=0))
RAISERROR('BAD FORM OF PESEL',1,1)
IF (SELECT SUM(CONVERT(INT, SUBSTRING(#pesel, position,1))*weight)%10
FROM #WEIGHTS)!=0
RAISERROR('BAD FORM OF PESEL',1,1)
FETCH NEXT FROM cursor_pesel INTO #pesel <--------
END
CLOSE cursor_pesel
Related
I have a problem with FETCH I am using this:
DECLARE Something CURSOR FOR
SELECT * FROM tblSomething
OPEN Something
WHILE ##FETCH_STATUS = 0
BEGIN
--CALL ANOTHER PROCEDURE
FETCH NEXT FROM Something
END
CLOSE Something
DEALLOCATE Something
The problem is 10 rows are in the table and 11 rows come out, the 11th row is blank data. I think it goes to fetch the next row and realises there isnt a next row. I need some sort of:
IF FETCH_ROWS = MAX then STOP
or something along those lines.
Try adding a FETCH NEXT FROM between OPEN and WHILE:
DECLARE Something CURSOR FOR
SELECT * FROM tblSomething
OPEN Something
FETCH NEXT FROM Something -- <== add this line
WHILE ##FETCH_STATUS = 0
BEGIN
--CALL ANOTHER PROCEDURE
FETCH NEXT FROM Something
END
CLOSE Something
DEALLOCATE Something
Here is a simple demonstration with a 10 rows table and a cursor that reads each row and prints the corresponding ID:
declare #tmp table (row_id int)
insert into #tmp values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)
DECLARE #myID as int;
DECLARE #wf_Cursor as CURSOR;
SET #wf_Cursor = CURSOR FOR SELECT row_id FROM #tmp
OPEN #wf_Cursor;
FETCH NEXT FROM #wf_Cursor INTO #myID;
WHILE ##FETCH_STATUS = 0
BEGIN
print('Reading row: ' + cast(#myID as nvarchar(10)));
FETCH NEXT FROM #wf_Cursor INTO #myID;
END
CLOSE #wf_Cursor;
DEALLOCATE #wf_Cursor;
Output:
So, I have the following problem:
I have 4 tables: Range Information, Range Percentage, DGRange and SGRange
Range information has a 1 - N to Range Percentage ( IE: N percentages to 1 range )
Both DGRange and SGRange connect these two tables to other external fonts.
It shouldn't be that way. But that is the way the system was built, and now I can only fix the problems that appear on that stupid decision.
In any case, we found times that both DGRange and SGRange are pointed to the same primary key when they shouldnt - and as such, once the system changes any information from that range it screws up something else in the system. As such, I must find out every time we have this duplicates ( very easy to do ) and duplicate the whole record on RangeInformation/RangePercentage and point one of them to the new record.
My problem is that right now I am thinking of using a cursor inside a cursor, and I believe that there may be a easier way to do it.
Is there a better way?
DECLARE #range nvarchar(10)
DECLARE #rangeinfoid nvarchar(10)
DECLARE #lowerlimit money
DECLARE #Upperlimit money
DECLARE #CurrentYear smallint
DECLARE #Percentage float
DECLARE subgroup_cursor CURSOR FOR
SELECT distinct a.RangeInformationId
FROM SubgroupRange a, DiscountGroupRange b
where a.RangeInformationId = b.RangeInformationId
DECLARE rangeperc_cursor CURSOR FOR
SELECT CurrentYear,
Percentage
from RangePercentage
where RangeInformationId = #range
OPEN subgroup_cursor
FETCH NEXT FROM subgroup_cursor INTO #range
WHILE ##FETCH_STATUS = 0
BEGIN
select #rangeinfoid = RangeInformationId ,
#lowerlimit = LowerLimit,
#Upperlimit = UpperLimit
from RangeInformation
where RangeInformationId = #range
--Add insert here
OPEN rangeperc_cursor
FETCH NEXT FROM subgroup_cursor INTO #CurrentYear, #Percentage
WHILE ##FETCH_STATUS = 0
BEGIN
print(#CurrentYear)
print(#Percentage)
--Add insert here
FETCH NEXT FROM rangeperc_cursor INTO #CurrentYear, #Percentage
END
FETCH NEXT FROM subgroup_cursor INTO #range
END
CLOSE subgroup_cursor
DEALLOCATE subgroup_cursor
CLOSE rangeperc_cursor
DEALLOCATE rangeperc_cursor
As I commented above this is difficult to know exactly what you are trying to do but does something like this get you the data you need?
select ri.RangeInformationId
, ri.LowerLimit
, ri.UpperLimit
from RangeInformation ri
join SubgroupRange sr on sr.RangeInformationId = ri.RangeInformationId
join DiscountGroupRange dgr on dgr.RangeInformationId = sr.RangeInformationId
You really should get on the habit of this style of join. It is a little cleaner code wise and helps prevent the accidental cross join by forgetting the join predicates as a where clause.
Here is an example of the comment I left, for clarity.
Essentially, try removing the subgroup_cursor altogether by creating the same population in a temp table:
DECLARE #rangeinfoid int
DECLARE #CurrentYear smallint
DECLARE #Percentage float
CREATE TABLE #temp_subgroup
(
RangeInformationID int
)
INSERT INTO #temp_subgroup
(RangeInformationID)
SELECT distinct a.RangeInformationId
FROM SubgroupRange a, DiscountGroupRange b
where a.RangeInformationId = b.RangeInformationId
DECLARE rangeperc_cursor CURSOR FOR
SELECT CurrentYear,
Percentage,
RangeInformationID
from RangePercentage
where RangeInformationId IN (SELECT RangeInformationID FROM #temp_subgroup)
OPEN rangeperc_cursor
WHILE (##FETCH_STATUS <> 0)
BEGIN
FETCH NEXT FROM rangeperc_cursor INTO #rangeinfoid, #CurrentYear, #Percentage
CREATE TABLE #temp_rangeupdate
(
RangeInformationID int,
LowerLimit money,
UpperLimit money
)
INSERT INTO #temp_rangeupdate
( RangeInformationID, LowerLimit, UpperLimit)
SELECT RangeInformationID,
LowerLimit,
UpperLimit
FROM RangeInformation
WHERE RangeInformationID = #rangeinfoid
-- UPDATE/INSERT #temp_rangeupdate
-- UPDATE/INSERT Production Tables from #temp_rangeupdate
DROP TABLE #temp_rangeupdate
END
DROP TABLE #temp_subgroup
CLOSE rangeperc_cursor
DEALLOCATE rangeperc_cursor
In a stored procedure, I have the following cursor:
DECLARE #cur CURSOR
SET #cur = CURSOR LOCAL FORWARD_ONLY READ_ONLY
FOR SELECT -- various columns
FROM #localTableVariable
...and then I open it, iterate, and close it. (Yes, I have a reason for iterating rather than doing set operations.)
If an error occurs, will that cursor get closed/cleaned up? I don't see anything about that in, say, the MSDN page on CLOSE. Or do I need to implement a TRY/CATCH and close it in the stored procedure code? (And then RAISEERROR to allow the error to allow the error to propagate to our usual error handling.)
I figure the answer has to be "yes, it'll get cleaned up," but...
Would the answer be the same if the cursor were for a real table rather than a table variable?
(This is within an explicit transaction where the procedure has SET XACT_ABORT ON, if that's relevant. Edit: And it appears that for my specific use case, I can be sure it'll get closed by using SET CURSOR_CLOSE_ON_COMMIT ON, because my transaction will be committed or rolled back by the end of my stored procedure. But I'm curious about the general case.)
Based on the very useful comment from SubqueryCrunch, I've empirically proved that the cursor gets cleaned up (without all the transaction stuff), at least on SQL Server 2012 with the options we're using:
CREATE PROCEDURE tjtemp
AS
BEGIN
DECLARE #foo TABLE
(
id INT
)
DECLARE #id INT
INSERT INTO #foo (id)
VALUES (1), (2), (3), (4), (5), (6)
DECLARE cur CURSOR LOCAL FORWARD_ONLY READ_ONLY
FOR SELECT id FROM #foo
OPEN cur
SELECT 'inside' AS Label, * FROM sys.dm_exec_cursors(0) WHERE name = 'cur'
FETCH NEXT FROM cur INTO #id
WHILE ##fetch_status = 0
BEGIN
PRINT #id
IF #id = 4
RAISERROR(N'ack!', 18, 1);
FETCH NEXT FROM cur INTO #id
END
CLOSE cur
END
GO
SELECT 'before' AS Label, * FROM sys.dm_exec_cursors(0) WHERE name = 'cur'
GO
EXEC tjtemp
GO
SELECT 'after' AS Label, * FROM sys.dm_exec_cursors(0) WHERE name = 'cur'
GO
(That's with a named cursor rather than a cursor variable, but see below.)
Results:
Messages:
(0 row(s) affected)
(6 row(s) affected)
(1 row(s) affected)
1
2
3
4
Msg 50000, Level 18, State 1, Procedure tjtemp, Line 24
ack!
(0 row(s) affected)
We can see that the cursor doesn't exist before the procedure is started, exists when the procedure has it open, and doesn't exist after the procedure has terminated with an error.
I'd prefer finding something in the docs, but this supports the "surely it has to work that way" gut feeling.
It turns out that with a cursor variable, the name column in dm_exec_cursors gets the variable's name, so I was able to prove it for the variable as well:
DROP PROCEDURE tjtemp
GO
CREATE PROCEDURE tjtemp
AS
BEGIN
DECLARE #foo TABLE
(
id INT
)
DECLARE #id INT
DECLARE #cur CURSOR
INSERT INTO #foo (id)
VALUES (1), (2), (3), (4), (5), (6)
SET #cur = CURSOR LOCAL FORWARD_ONLY READ_ONLY
FOR SELECT id FROM #foo
OPEN #cur
SELECT 'inside' AS Label, * FROM sys.dm_exec_cursors(0) WHERE name = '#cur'
FETCH NEXT FROM #cur INTO #id
WHILE ##fetch_status = 0
BEGIN
PRINT #id
IF #id = 4
RAISERROR(N'ack!', 18, 1);
FETCH NEXT FROM #cur INTO #id
END
CLOSE #cur
END
GO
SELECT 'before' AS Label, * FROM sys.dm_exec_cursors(0) WHERE name = '#cur'
GO
EXEC tjtemp
GO
SELECT 'after' AS Label, * FROM sys.dm_exec_cursors(0) WHERE name = '#cur'
GO
(Same results.)
But I also did a run without any WHERE clause on the selects from dm_exec_cursors (when no one else was doing anything on the DB), just to be sure.
Is there any option to search inside cursor?
For example: I have a table(MyTable) with row number and value,
that I want to copy to another table(TestTable),
but let's say that if there was a value >= 5 then the next value,
that I want to copy should be <= 3.
I can use something like this:
create table TestTable
(row tinyint,
value tinyint)
declare #row tinyint, #value tinyint, #trigger bit
declare test_cursor cursor fast_forward for
select row,value from MyTable order by row
open test_cursor
fetch next from test_cursor into #row,#value
set #trigger = 0
while ##FETCH_STATUS = 0
begin
if #trigger = 0
begin
insert into TestTable values (#row,#value)
if #value >= 5 set #trigger = 1
end
else if #value <= 3
begin
insert into TestTable values (#row,#value)
set #trigger = 0
end
fetch next from test_cursor into #row,#value
end
close test_cursor
deallocate test_cursor
That will work, but my question is: is there an any way to search inside cursor
for the next falue that <= 3 once trigger = 1,
instead of fetching next row over and over every time?
No, cursors don't support the kind of querying that you're after. You will have to visit each value and check it in the loop.
The code posted here is 'example' code, it's not production code. I've done this to make the problem I'm explaining readable / concise.
Using code similar to that below, we're coming across a strange bug. After every INSERT the WHILE loop is stopped.
table containst 100 rows, when the insert is done after 50 rows then the cursor stops, having only touched the first 50 rows. When the insert is done after 55 it stops after 55, and so on.
-- This code is an hypothetical example written to express
-- an problem seen in production
DECLARE #v1 int
DECLARE #v2 int
DECLARE MyCursor CURSOR FAST_FORWARD FOR
SELECT Col1, Col2
FROM table
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO #v1, #v2
WHILE(##FETCH_STATUS=0)
BEGIN
IF(#v1>10)
BEGIN
INSERT INTO table2(col1) VALUES (#v2)
END
FETCH NEXT FROM MyCursor INTO #v1, #v2
END
CLOSE MyCursor
DEALLOCATE MyCursor
There is an AFTER INSERT trigger on table2 which is used to log mutaties on table2 into an third table, aptly named mutations. This contains an cursor which inserts to handle the insert (mutations are logged per-column in an very specific manner, which requires the cursor).
A bit of background: this exists on an set of small support tables. It is an requirement for the project that every change made to the source data is logged, for auditing purposes. The tables with the logging contain things such as bank account numbers, into which vast sums of money will be deposited. There are maximum a few thousand records, and they should only be modified very rarely. The auditing functionality is there to discourage fraud: as we log 'what changed' with 'who did it'.
The obvious, fast and logical way to implement this would be to store the entire row each time an update is made. Then we wouldn't need the cursor, and it would perform an factor better. However the politics of the situation means my hands are tied.
Phew. Now back to the question.
Simplified version of the trigger (real version does an insert per column, and it also inserts the old value):
--This cursor is an hypothetical cursor written to express
--an problem seen in production.
--On UPDATE a new record must be added to table Mutaties for
--every row in every column in the database. This is required
--for auditing purposes.
--An set-based approach which stores the previous state of the row
--is expressly forbidden by the customer
DECLARE #col1 int
DECLARE #col2 int
DECLARE #col1_old int
DECLARE #col2_old int
--Loop through old values next to new values
DECLARE MyTriggerCursor CURSOR FAST_FORWARD FOR
SELECT i.col1, i.col2, d.col1 as col1_old, d.col2 as col2_old
FROM Inserted i
INNER JOIN Deleted d ON i.id=d.id
OPEN MyTriggerCursor
FETCH NEXT FROM MyTriggerCursor INTO #col1, #col2, #col1_old, #col2_old
--Loop through all rows which were updated
WHILE(##FETCH_STATUS=0)
BEGIN
--In production code a few more details are logged, such as userid, times etc etc
--First column
INSERT Mutaties (tablename, columnname, newvalue, oldvalue)
VALUES ('table2', 'col1', #col1, #col1_old)
--Second column
INSERT Mutaties (tablename, columnname, newvalue, oldvalue)
VALUES ('table2', 'col2', #col2, #col1_old)
FETCH NEXT FROM MyTriggerCursor INTO #col1, #col2, #col1_old, #col2_old
END
CLOSE MyTriggerCursor
DEALLOCATE MyTriggerCursor
Why is the code exiting in the middle of the loop?
Your problem is that you should NOT be using a cursor for this at all! This is the code for the example given above.
INSERT INTO table2(col1)
SELECT Col1 FROM table
where col1>10
You also should never ever use a cursor in a trigger, that will kill performance. If someone added 100,000 rows in an insert this could take minutes (or even hours) instead of millseconds or seconds. We replaced one here (that predated my coming to this job) and reduced an import to that table from 40 minites to 45 seconds.
Any production code that uses a cursor should be examined to replace it with correct set-based code. in my experience 90+% of all cursors can be reqwritten in a set-based fashion.
Ryan, your problem is that ##FETCH_STATUS is global to all cursors in an connection.
So the cursor within the trigger ends with an ##FETCH_STATUS of -1. When control returns to the code above, the last ##FETCH_STATUS was -1 so the cursor ends.
That's explained in the documentation, which can be found on MSDN here.
What you can do is use an local variable to store the ##FETCH_STATUS, and put that local variable in the loop. So you get something like this:
DECLARE #v1 int
DECLARE #v2 int
DECLARE #FetchStatus int
DECLARE MyCursor CURSOR FAST_FORWARD FOR
SELECT Col1, Col2
FROM table
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO #v1, #v2
SET #FetchStatus = ##FETCH_STATUS
WHILE(#FetchStatus=0)
BEGIN
IF(#v1>10)
BEGIN
INSERT INTO table2(col1) VALUES (#v2)
END
FETCH NEXT FROM MyCursor INTO #v1, #v2
SET #FetchStatus = ##FETCH_STATUS
END
CLOSE MyCursor
DEALLOCATE MyCursor
It's worth noting that this behaviour does not apply to nested cursors. I've made an quick example, which on SqlServer 2008 returns the expected result (50).
USE AdventureWorks
GO
DECLARE #LocationId smallint
DECLARE #ProductId smallint
DECLARE #Counter int
SET #Counter=0
DECLARE MyFirstCursor CURSOR FOR
SELECT TOP 10 LocationId
FROM Production.Location
OPEN MyFirstCursor
FETCH NEXT FROM MyFirstCursor INTO #LocationId
WHILE (##FETCH_STATUS=0)
BEGIN
DECLARE MySecondCursor CURSOR FOR
SELECT TOP 5 ProductID
FROM Production.Product
OPEN MySecondCursor
FETCH NEXT FROM MySecondCursor INTO #ProductId
WHILE(##FETCH_STATUS=0)
BEGIN
SET #Counter=#Counter+1
FETCH NEXT FROM MySecondCursor INTO #ProductId
END
CLOSE MySecondCursor
DEALLOCATE MySecondCursor
FETCH NEXT FROM MyFirstCursor INTO #LocationId
END
CLOSE MyFirstCursor
DEALLOCATE MyFirstCursor
--
--Against the initial version of AdventureWorks, counter should be 50.
--
IF(#Counter=50)
PRINT 'All is good with the world'
ELSE
PRINT 'Something''s wrong with the world today'
this is a simple misunderstanding of triggers... you don't need a cursor at all for this
if UPDATE(Col1)
begin
insert into mutaties
(
tablename,
columnname,
newvalue
)
select
'table2',
coalesce(d.Col1,''),
coalesce(i.Col1,''),
getdate()
from inserted i
join deleted d on i.ID=d.ID
and coalesce(d.Col1,-666)<>coalesce(i.Col1,-666)
end
basically what this code does is it checks to see if that column's data was updated. if it was, it compares the new and old data, and if it's different it inserts into your log table.
you're first code example could easily be replaced with something like this
insert into table2 (col1)
select Col2
from table
where Col1>10
This code does not fetch any further values from the cursor, nor does it increment any values. As it is, there is no reason to implement a cursor here.
Your entire code could be rewritten as:
DECLARE #v1 int
DECLARE #v2 int
SELECT #v1 = Col1, #v2 = Col2
FROM table
IF(#v1>10)
INSERT INTO table2(col1) VALUES (#v2)
Edit: Post has been edited to fix the problem I was referring to.
You do not have to use a cursor to insert each column as a separate row.
Here is an example:
INSERT LOG.DataChanges
SELECT
SchemaName = 'Schemaname',
TableName = 'TableName',
ColumnName = CASE ColumnID WHEN 1 THEN 'Column1' WHEN 2 THEN 'Column2' WHEN 3 THEN 'Column3' WHEN 4 THEN 'Column4' END
ID = Key1,
ID2 = Key2,
ID3 = Key3,
DataBefore = CASE ColumnID WHEN 1 THEN I.Column1 WHEN 2 THEN I.Column2 WHEN 3 THEN I.Column3 WHEN 4 THEN I.Column4 END,
DataAfter = CASE ColumnID WHEN 1 THEN D.Column1 WHEN 2 THEN D.Column2 WHEN 3 THEN D.Column3 WHEN 4 THEN D.Column4 END,
DateChange = GETDATE(),
USER = WhateverFunctionYouAreUsingForThis
FROM
Inserted I
FULL JOIN Deleted D ON I.Key1 = D.Key1 AND I.Key2 = D.Key2
CROSS JOIN (
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
) X (ColumnID)
In the X table, you could code additional behavior with a second column that specially describes how to handle just that column (let's say you wanted some to post all the time, but others only when the value changes). What's important is that this is an example of the cross join technique of splitting rows into each column, but there is a lot more that can be done. Note that the full join allows this to work on inserts and deletes as well as updates.
I also fully agree that storing each row is FAR superior. See this forum for more about this.
As ck mentioned, you are not fetching any further values. The ##FETCH_STATUS thus get's its value from your cursor contained in your AFTER INSERT trigger.
You should change your code to
DECLARE #v1 int
DECLARE #v2 int
DECLARE MyCursor CURSOR FAST_FORWARD FOR
SELECT Col1, Col2
FROM table
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO #v1, #v2
WHILE(##FETCH_STATUS=0)
BEGIN
IF(#v1>10)
BEGIN
INSERT INTO table2(col1) VALUES (#v2)
END
FETCH NEXT FROM MyCursor INTO #v1, #v2
END