I'm trying to insert invoice items to existing invoice with negative value for quantity. I decided to use cursor for this but when I run the query it results in infinite loop.
Here is my code:
declare #cKey char(13);
set #cKey = '1512000000043';
-- declare cursor to get
-- all items for specific invoice
declare c cursor
for
select
acIdent, anQty
from
tHE_MoveItem where acKey = #cKey;
declare #cIdent char (16),
#nQty decimal(19,6),
#nNo int,
#cStatus varchar(2),
#cErrorOut varchar(1024);
open c
fetch c into #cIdent, #nQty
while (##fetch_status=0)
begin
-- add all items with negative qty
-- to same invoice
select #cIdent;
-- invert value
set #nQty = #nQty *-1;
select #nQty;
-- insert ident with negative value to invoice
EXEC dbo.pHE_MoveItemsCreAll #cKey, #cIdent,#nQty, '', 1, #nNo OUTPUT,#cErrorOut OUTPUT,#cStatus OUTPUT;
fetch c into #cIdent, #nQty
end
close c
deallocate c
I'm using SQL Server 2008 R2.
The procedure pHE_MoveItemsCreAll is inserting values in same table as the cursor reads from.
You have to declare your cursor using static keyword (declare c cursor static) to prevent fetching newly inserted records back to cursor.
A static cursor always displays the result set as it was when the cursor was opened. In other case when you're inserting your records into the same table and they met conditions of data selected into cursor - these new records will be retrieved and cursor iterates again.
Related
I have a stored procedure that I need to run a list of values through and output into a temp table.
This is the SP: EXEC [SP_ReturnHTML] #zoneid, 1
The first value, I assume, will be a variable and the second value will be hard-coded. I am not able to modify this SP, as it is used in other processes, so I need to run these values through the SP via a cursor or WHILE loop. The values only need to be run through once, so a FAST_FORWARD cursor type may be more ideal, based on some preliminary reading on cursors (of which my experience in is extremely limited). This is what I attempted:
declare #zoneid int = (select zoneid from #values)
declare list cursor fast_forward
for EXEC [SP_ReturnHTML] #zoneid,1
open list
fetch next from list
But when I try to do this, I get the error Incorrect syntax near the keyword 'EXEC'.
The output of this SP, when using #zoneid=14105 (and the hard-coded 1 relates to the fieldgroupid) looks something like the shot below. For clarity, despite using #zoneid=14105, the reason a value of 4054 shows up is due to the way the SP is written, and is intended. The two values relate to a state and county relationship, noted by the first 2 columns, ParentHeaderId and HeaderId. I opted to use 14105 for the example, because the 3 examples in the #values table only retrieve their secondary value and I wanted to avoid confusion here.
The values that I need to run through the SP for the #zoneid are in a table (which has about 3100 rows), which can be exemplified with the following:
create table #values (zoneid int)
insert into #values
values
(13346),
(13347),
(13348)
So very simply put, I need something like the following as a final product (pseudo code):
declare #zoneid INT = (select zoneid from #values)
select * into #results from
(
EXEC [SP_ReturnHTML] #zoneid, 1
)
Something like this:
drop table if exists #results
drop table if exists #Data
go
create or alter procedure [SP_ReturnHTML] #value int, #s varchar(20)
as
begin
select concat(' value=',#value, '; s = ', #s)
end
go
create table #Data (value int, county varchar(30))
insert into #Data
values
(100, 'Baker'),
(101,'Baldwin'),
(102,'Baldwin'),
(103,'Ballard'),
(104,'Baltimore City'),
(105,'Baltimore'),
(106,'Bamberg'),
(107,'Bandera'),
(108,'Banders'),
(109,'Banks'),
(110,'Banner'),
(111,'Bannock'),
(112,'Baraga')
go
create table #results(value nvarchar(200))
declare c cursor local for select value from #Data
declare #value int
open c
fetch next from c into #value
while ##fetch_status = 0
begin
insert into #results(value)
EXEC [SP_ReturnHTML] #value, '1'
fetch next from c into #value
end
go
select *
from #results
I am trying to convert an SQL that was written for a previous version of our software. It is grabbing information from an input form, placing them in a temporary table and calculating number of labels and printing a crystal report label accordingly
I have tried changing syntax and removing a where clause ( it is commented out in my code below) that i was unable to link to anything in our new version.
SET NOCOUNT ON
DECLARE #nloop int, #nLabels int
DECLARE #rmlReceiptID varchar(10), #rmlReceiptLineID int, #urmlNOofLabels int
DECLARE LabelsCursor CURSOR READ_ONLY FOR SELECT #rmlReceiptID, #rmlReceiptLineID, #urmlNOofLabels FROM ReceiptLines /* WHERE {?WHERECLAUSE}*/ ORDER BY rmlReceiptID, rmlReceiptLineID
CREATE TABLE #UReceiptLabel (rmlReceiptID varchar(10), rmlReceiptLineID int, CurrentLabel int, TotalLabels int)
SELECT #rmlReceiptID,#rmlReceiptLineID,CONVERT(int,0) As CurrentLabel,CONVERT(int,0) As TotalLabels insert into #UReceiptLabel from ReceiptLines WHERE 0=1
OPEN LabelsCursor
FETCH NEXT FROM LabelsCursor INTO #rmlReceiptID, #rmlReceiptLineID, #urmlNOofLabels
WHILE ##FETCH_STATUS = 0
BEGIN
SET #nloop = 0
SET #nLabels = #urmlNOofLabels
IF #nLabels < 1
SET #nLabels = 1
WHILE (#nloop < #nLabels)
BEGIN
SET #nloop = #nloop + 1
INSERT INTO #UReceiptLabel (rmlReceiptID, rmlReceiptLineID, CurrentLabel, TotalLabels) VALUES (#rmlReceiptID, #rmlReceiptLineID, #nloop, #nLabels)
END
FETCH NEXT FROM LabelsCursor INTO #rmlReceiptID, #rmlReceiptLineID, #urmlNOofLabels
END
CLOSE LabelsCursor
DEALLOCATE LabelsCursor
SET NOCOUNT OFF
SELECT CurrentLabel, TotalLabels, ReceiptLines.rmlReceiptID, ReceiptLines.rmlReceiptLineID, rmlJobID, rmlPartID, rmlJobQuantityReceived, urmlNoOfLabels, urmlQtyInABox, urmlLocation,rmpSupplierOrganizationID, cmoName, rmlDescription, rmlJobAssemblyID
FROM #UReceiptLabel
INNER JOIN ReceiptLines ON ReceiptLines.rmlReceiptID = #UReceiptLabel.rmlReceiptID and ReceiptLines.rmlReceiptLineID = #UReceiptLabel.rmlReceiptLineID
LEFT OUTER JOIN Receipts ON rmpReceiptID = #UReceiptLabel.rmlReceiptID
LEFT OUTER JOIN Organizations On rmpSupplierOrganizationID=cmoOrganizationID ORDER BY #UReceiptLabel.rmlReceiptID,#UReceiptLabel.rmlReceiptLineID,CurrentLabel
DROP TABLE #UReceiptLabel
when i attempt to run the crystal report i get An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name.
I would expect the crystal report to parse the input data and fill the label with appropriate information and print the correct number of labels.
I'm busy trying to rewrite some PostgreSQL stored procedures/functions for SQL Server 2014s TSQL.
I am struggling to return my values from this stored procedure though, this one is just a test but I am trying to return multiple rows of data in this case the for the two variables si_code and co_desc.
I have my procedure as follows (as a test)
if (object_id('p_get_serial')) is not null
drop procedure p_get_serial
go
create procedure p_get_serial(#par01 char(20), #par02 integer)
as
declare
#co_num integer,
#co_desc char(20),
#si_code char(20),
#log char(40)
declare mycur cursor for
select co_num, co_desc
from colours
where co_num <= #par02
open mycur
fetch next from mycur into #co_num,
#co_desc
while ##FETCH_STATUS = 0
begin
set #si_code = ''
select #si_code = si_code
from sitems
where si_co_num = #co_num
set #log = #co_desc + ' ' + #si_code
raiserror(#log,0,1) with nowait
fetch next from mycur into #co_num, #co_desc
end
close mycur deallocate mycur
go
exec p_get_serial #par01 = 'paramater01', #par02 = 10
what is the best way to return my results knowing that there will be several rows?
In T-SQL you do not need to declare a cursor. Just select what you need and it will be available to the client app.
Cursor is Oracle/DB2/PostgreSQL etc way of returning data. SQL Server does not need it.
create procedure p
as
select 1 as a
returns a recordset containing one record with one column.
create procedure p
as
select 1 as a, 'a' as b
union select 2, 'b'
returns two rows each with two columns.
Example of a more complex processing before returning a result set:
create procedure p
as
begin
declare #a int, #b varchar(10)
select #a = 1
select #b = convert(varchar(10), #a)
select #a = #a + 1
select #a as a, #b as b -- this will be the resultset returned to the client
end
All you need to do is, just save the data for each row in a temp table or table variable and just write a SELECT statement at the the end of the Stored Procedure.
Your question is not clear what you need exactly, you have a cursor and while loop, they seem to be redundant
How to go about auto populating student's roll number column in ascending order from 1,2,3... and so on on assign button click in the form ?
TABLE
How the cursor will be invoked?
I'm using stored procedures for all database operations.
SAMPLE CODE
declare #studID int
declare rollCursor CURSOR FOR
select * from TESTING
OPEN rollCursor
If you want a single StudentId, just write in your procedure
-- Where #StudendId will be parameter to your stored procedure
SELECT * FROM TESTING
WHERE StudId = #StudendId
Here is how you can use CURSOR. But note, CURSOR have performance issues. So use it rarely.
DECLARE #StudId INT
DECLARE #FName VARCHAR(50)
DECLARE #ROLL INT
-- Here you declare which all columns you need to loop in Cursor
DECLARE rollCursor CURSOR FOR
select * from TESTING
WHERE StudId = #StudendId
ORDER BY StudId;
OPEN rollCursor
-- Loop starts from here
FETCH NEXT FROM rollCursor
INTO #StudId,#FName,#ROLL
WHILE ##FETCH_STATUS = 0
BEGIN
-- Select studentid one by one from the table
SELECT * FROM TESTING
WHERE StudId = #StudId
-- Fetches next record and increments the loop
FETCH NEXT FROM rollCursor
INTO #StudId,#FName,#ROLL
END
CLOSE rollCursor;
DEALLOCATE rollCursor;
EDIT : 1 (Getting Row number for table)
If you need the result according to the roll then use the below query
-- This will bring you the records with roll number in ascending order
-- If you want in descending order just change ASC to DESC
SELECT studid,Fname,ROW_NUMBER() OVER(ORDER BY roll ASC) roll
FROM StudId
EDIT : 2 (Create identity field)
You need to set roll number column as Identity field, ie a column with an integer value which automatically increments value on new insertions.
Once you set the roll number column as Identity field, try with the below inserts
INSERT INTO TESTING(StudId,Fname)VALUES(10,'A')
INSERT INTO TESTING(StudId,Fname)VALUES(10,'A')
You will not select or include the roll number column in insert. It will automatically increment.
Click here to view more on identity field
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