This is my Coding...
If i execute the Stored procedure which means with in the stored procedure
(Normally selecting everything and if i press execute button at top of the menu)
it is working
but
out side
how can i run the stored procedure.
i tried like this
exec uspGetAddress 'CDB0001','Bevcon Wayors Pvt Ltd','c'
but not working.
SET NOCOUNT ON
DECLARE #Cuscode varchar(250)
DECLARE #customertName VARCHAR(250)
DECLARE #custype varchar(250)
DECLARE #Cur_Product CURSOR
set #Cur_Product= cursor for select CardCode,CardName,CardType from ocrd
open #Cur_Product
fetch next
from #Cur_Product into #Cuscode,#customertName,#custype
while ##FETCH_STATUS = 0
begin
insert into custupdate (ccode,cname,ctype) values (#Cuscode,#customertName,#custype)
fetch next
from #Cur_Product into #Cuscode,#customertName,#custype
end
close #Cur_Product
deallocate #Cur_Product
You have to create the Stored Procedure before calling it :
Create Procedure uspGetAddress
#Cuscode varchar(250),
#customertName VARCHAR(250) ,
#custype varchar(250)
As
Begin
DECLARE #Cur_Product CURSOR
set #Cur_Product= cursor for select CardCode,CardName,CardType from ocrd
open #Cur_Product
fetch next
from #Cur_Product into #Cuscode,#customertName,#custype
while ##FETCH_STATUS = 0
begin
insert into custupdate (ccode,cname,ctype) values (#Cuscode,#customertName,#custype)
fetch next
from #Cur_Product into #Cuscode,#customertName,#custype
end
close #Cur_Product
deallocate #Cur_Product
End
Related
I want to write a script to make stored procedures for insert , delete and update every single table of Information _ Schema , I came up with this code but I have problems in procedures input parameters and the way to insert , delete and update them, can anyone help me please?
DECLARE AutoProc CURSOR GLOBAL
FOR
SELECT TABLE_SCHEMA,TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
OPEN AutoProc
DECLARE #Schema NVARCHAR(100)
DECLARE #Table NVARCHAR(100)
DECLARE #TotalField NVARCHAR(600)=''
DECLARE #Parameters NVARCHAR(600)
FETCH NEXT
FROM AutoProc
INTO #Schema,#Table
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE AutoFields CURSOR GLOBAL
FOR
SELECT COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA=#Schema AND
TABLE_NAME=#Table AND
TABLE_NAME
IN
(
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE= 'BASE TABLE'
)
OPEN AutoFields
DECLARE #FieldName NVARCHAR(100)
DECLARE #DataType NVARCHAR(50)
DECLARE #Size NVARCHAR(10)
FETCH NEXT
FROM AutoFields
INTO #FieldName,#DataType,#Size
WHILE ##FETCH_STATUS = 0
BEGIN
IF #DataType='NVARCHAR' OR #DataType='nvarchar'
BEGIN
SET #TotalField=#TotalField+'#'+#FieldName+' '+#DataType+'('+#Size+'),'
END
ELSE
BEGIN
SET #TotalField=#TotalField+'#'+#FieldName+' '+#DataType+','
END
FETCH NEXT
FROM AutoFields
INTO #FieldName,#DataType,#Size
END
CLOSE AutoFields
DEALLOCATE AutoFields
SET #Parameters =SUBSTRING(#TotalField,1,LEN(#TotalField)-1)
EXECUTE('
CREATE PROC USP_INS_'+#Schema+'_'+#Table+'
#parameters NVARCHAR(600)='+#Parameters+'
AS
BEGIN
INSERT '+#Schema+'.'+#Table+'
VALUES(#parameters)
END')
EXECUTE('
CREATE PROC USP_UPD_'+#Schema+'_'+#Table+'
#parameters NVARCHAR(600)='+#Parameters+'
AS
BEGIN
UPDATE '+#Schema+'.'+#Table+'
SET
END')
EXECUTE('
CREATE PROC USP_DEL_'+#Schema+'_'+#Table+'
parameters NVARCHAR(600)='+#Parameters+'
AS
BEGIN
DELETE '+#Schema+'.'+#Table+'
WHERE
END')
SET #TotalField=''
FETCH NEXT
FROM AutoProc
INTO #Schema,#Table
END
CLOSE AutoProc
DEALLOCATE AutoProc
I am using SQL Server 2012: This is the query using cursors.
create table test(id varchar(10), name varchar(10))
insert into test values('1','a'),('2','b'),('3','c')
declare #id varchar(10)
declare #name varchar(10)
declare cur cursor for
select id, name
from test
open cur
if ##CURSOR_ROWS > 0
begin
fetch next from cur into #id, #name
while ##FETCH_STATUS=0
begin
print 'test'
print #id+','+#name
fetch next from cur into #id,#name
end
end
close cur
deallocate cur
But in the result set it doesn't display results, but gets successfully executed.
Expected result
1,a
2,b
3,c
##CURSOR_ROWS is returning -1 that's why it's not printing.
Try this:
declare #id varchar(10)
declare #name varchar(10)
declare cur cursor for
select id, name from test
open cur
fetch next from cur into #id, #name
while ##FETCH_STATUS = 0
begin
print #id+','+#name
fetch next from cur into #id,#name
end
close cur
deallocate cur
Read more about ##CURSOR_ROWS.
i have one procedure name Randomoutlet and i want to call that procedure via other procedure as code below
ALTER procedure [dbo].[MainSchedule]
as
begin
DECLARE #sup table (supervisorId int)
INSERT INTO #sup SELECT DISTINCT SupervisorId FROM CallPlan .dbo .CallPlanSchedule WHERE MONTH (scheduledate)= MONTH (GETDATE ()) and YEAR (ScheduleDate )= YEAR(GETDATE())
DECLARE CUR CURSOR FORWARD_ONLY FOR SELECT * FROM #sup
DECLARE #suptem int
OPEN CUR
FETCH NEXT FROM CUR INTO #suptem
WHILE ##FETCH_STATUS =0
BEGIN
EXEC [dbo].[randomOutlet] #suptem
FETCH NEXT FROM CUR INTO #suptem
END
CLOSE CUR
DEALLOCATE CUR
end
when i save MainSchedule it's show message "The module 'MainSchedule' depends on the missing object 'dbo.randomOutlet'. The module will still be created; however, it cannot run successfully until the object exists.
"
and when i run this procedure it's appear error "Msg 2812, Level 16, State 62, Procedure MainSchedule, Line 15
Could not find stored procedure 'dbo.randomOutlet'."
please help me solve this problem thank in advance
I tried the following and got everything running fine.
CREATE procedure CALL_PROC --'abc'
#var varchar(100)
as
begin
declare #sup table (item int)
insert into #sup select 1 union select 2
DECLARE CUR CURSOR FORWARD_ONLY FOR SELECT * FROM #sup
DECLARE #var1 int
OPEN CUR
FETCH NEXT FROM CUR INTO #var1
WHILE ##FETCH_STATUS =0
BEGIN
EXEC dbo.call_me #var1
FETCH NEXT FROM CUR INTO #var1
END
CLOSE CUR
DEALLOCATE CUR
end
go
CREATE PROCEDURE [dbo].[CALL_ME]
#VAR VARCHAR(100)
AS
if OBJECT_ID('tempdb..#temp') is not null
begin
insert into #temp select #VAR
end
else
select #var value into #temp
select * from #temp
go
Please check if you have created the objects on the same DB or not.
I have a query which processes XML data and I use a while(##FETCH_STATUS = 0) loop for data returned from the cursor.
When I run the query using Management Studio, ##FETCH_STATUS equals -1 and the code inside my loop is omitted. If I run the query using the debugger and press continue, it runs just fine and the ##FETCH_STATUS equals 0. When I run the query again, after running it in debug ##FETCH_STATUS equals 0 and changes to -1.
To sum up:
I run with SSMS - ##FETCH_STATUS = -1
I run with debugger - ##FETCH_STATUS = 0 (I want this value)
I run with SSMS once after running with debugger ##FETCH_STATUS still equals 0 but then changes to -1.
I use OPEN cursor, CLOSE cursor and DEALLOCATE cursor. Why does it work this way?
EDIT: Code you asked for:
IF (OBJECT_ID('dbo.XmlOrderResponses') IS NOT NULL)
DROP TABLE XmlOrderResponses;
CREATE TABLE XmlOrderResponses (
OrderResponseType INT
,OrderResponseNumber NVARCHAR(40)
,OrderResponseDate DATETIME
,DocumentFunctionCode NVARCHAR(40)
,Remarks INT
);
DECLARE CUR CURSOR
FOR
SELECT Subdirectory
FROM XMLFiles;
OPEN CUR
WHILE (##FETCH_STATUS = 0)
BEGIN
DECLARE #DocHandle AS INT;
DECLARE #TMP AS NVARCHAR(512);
FETCH NEXT
FROM Cur
INTO #TMP
DECLARE #XmlDocument AS NVARCHAR(MAX);
SET #XmlDocument = (
SELECT CAST(XMLSource AS NVARCHAR(max))
FROM XMLFiles
WHERE subdirectory = #TMP
);
EXEC sys.sp_xml_preparedocument #DocHandle OUTPUT
,#XmlDocument;
INSERT INTO XmlOrderResponses (
OrderResponseType
,OrderResponseNumber
,OrderResponseDate
,DocumentFunctionCode
,Remarks
)
SELECT *
FROM OPENXML(#DocHandle, '/Document-OrderResponse/*', 11) WITH (
OrderResponseType INT
,OrderResponseNumber NVARCHAR(40)
,OrderResponseDate DATETIME
,DocumentFunctionCode NVARCHAR(40)
,Remarks INT
);
EXEC sys.sp_xml_removedocument #DocHandle;
END
CLOSE CUR;
DEALLOCATE CUR;
--I know I shouldn't be doing that but I can't get rid of NULL records the other way.
DELETE
FROM XmlOrderResponses
WHERE OrderResponseType IS NULL
AND OrderResponseNumber IS NULL
AND OrderResponseDate IS NULL
AND DocumentFunctionCode IS NULL
AND Remarks IS NULL;
SELECT *
FROM XmlOrderResponses
SELECT ##FETCH_STATUS
The problem is that the first time you refer to ##FETCH_STATUS, you have not done a fetch with your cursor, so it is referring to the last cursor used. Imagine this simple example:
DECLARE C1 CURSOR
FOR
SELECT TOP 3 ID
FROM (VALUES ('1'), ('2'), ('3')) t (ID);
OPEN C1;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #c1 CHAR(1);
FETCH NEXT FROM C1 INTO #c1;
PRINT #c1;
END
CLOSE C1;
DEALLOCATE C1;
DECLARE C2 CURSOR
FOR
SELECT TOP 3 ID
FROM (VALUES ('1'), ('2'), ('3')) t (ID);
OPEN C2;
-- HERE ##FETCH_STATUS REFERS TO THE LAST FETCH FOR CURSOR `C1` NOT `C2`
SELECT ##FETCH_STATUS;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #c2 CHAR(1);
FETCH NEXT FROM C2 INTO #c2;
PRINT #c2;
END;
CLOSE C2;
DEALLOCATE C2;
At the commented line, even though you have closed, and deallocated C1, ##FETCH_STATUS is still referring to this cursor (since no other FETCH has been performed since), so you never enter your loop for C2
You should perform the Fetch before the loop, then at the end of each loop, rather than at the beginning.
DECLARE #TMP AS NVARCHAR(512);
OPEN CUR
-- DO FETCH FIRST
FETCH NEXT FROM Cur INTO #TMP
WHILE (##FETCH_STATUS = 0)
BEGIN
DECLARE #DocHandle AS INT;
-- DO ALL YOUR WORK WITH #TMP
--PERFORM THE FETCH AGAIN AT THE END OF THE LOOP
FETCH NEXT FROM Cur INTO #TMP
END
The other problem you have with doing FETCH at the start of each loop, is that the last item will be processed twice. Again a simple example (and assuming you enter the loop with ##FETCH_STATUS = 0)
DECLARE C1 CURSOR
FOR
SELECT ID = '1';
OPEN C1;
DECLARE #c CHAR(1);
WHILE (##FETCH_STATUS = 0)
BEGIN
DECLARE #c1 CHAR(1);
FETCH NEXT FROM C1 INTO #c1;
PRINT #c1;
END
This will print
1
1
Because, when ##FETCH_STATUS is -1, FETCH will just return the item at the current position.
I have the following table
Create table TestScene(
string varchar(60))
insert into TestScene values ('t_Scene');
insert into TestScene values ('v_Scene');
On this table,I want to parse each string and I'm doing that,the problem is that it's doubling the last field and I don't know why.Do you see what I'm missing?
DECLARE #contor int
DECLARE #stringut varchar(50)
DECLARE cursorName CURSOR -- Declare cursor
FOR
Select string FROM TestScene
Select #contor=count(*) from TestScene
OPEN cursorName -- open the cursor
print #contor
FETCH NEXT FROM cursorName INTO #stringut
PRINT #stringut+' ' -- print the name
WHILE #contor>0
BEGIN
FETCH NEXT FROM cursorName INTO #stringut
declare #i int,#j int
set #j=charindex(#stringut,'_')
set #i=0
While #j<>0
begin
declare #str varchar
set #str = SUBSTRING(#stringut,#i,#j-1-#i)
print #str+' '
set #i=#j
set #j=charindex(#stringut,'_')
end
PRINT #stringut -- print the name
set #contor=#contor-1
END
CLOSE cursorName -- close the cursor
DEALLOCATE cursorName -- Deallocate the cursor
That's becuase you have fetched value in cursor twice one before while loop and one within it. Write as:
DECLARE #contor int
DECLARE #stringut varchar(50)
DECLARE cursorName CURSOR -- Declare cursor
FOR
Select string FROM TestScene
Select #contor=count(*) from TestScene
OPEN cursorName -- open the cursor
print #contor
--FETCH NEXT FROM cursorName INTO #stringut-- no need
PRINT #stringut+' ' -- print the name
WHILE #contor>0
BEGIN
FETCH NEXT FROM cursorName INTO #stringut
declare #i int,#j int
set #j=charindex(#stringut,'_')
set #i=0
While #j<>0
begin
declare #str varchar
set #str = SUBSTRING(#stringut,#i,#j-1-#i)
print #str+' '
set #i=#j
set #j=charindex(#stringut,'_')
end
PRINT #stringut -- print the name
set #contor=#contor-1
END
CLOSE cursorName -- close the cursor
DEALLOCATE cursorName -- Deallocate the cursor