Stored Procedure Cursor Problem URGENT
Hi,
I have created the following stored procedure to get the text from one table and compare with them with another table and the one's that match will assign the corresponding ID. But the problem is that it only assigns the last id in the table from the main table which new_cur2 holds. So the problem is that its not updating with the correct ID its just updating with the last ID the cursor holds. Does any one know what it could be.....I think it may just be a little coding error....thanks
CREATE PROCEDURE [MYSP] AS
Declare @pdesc nvarchar(30)
Declare @ssc int
Declare @myid int
Declare @name nvarchar(30)
Declare new_cur CURSOR DYNAMIC FOR
SELECT ProductDescription, SubSubCatID
FROM C2000HPB
FOR UPDATE
Open new_cur
FETCH FROM new_cur INTO @pdesc, @ssc
While @@FETCH_STATUS = 0
BEGIN
Declare new_cur2 CURSOR DYNAMIC FOR
SELECT SubSubCatID, SubSubCategory FROM SSC
FOR READ ONLY
Open new_cur2
FETCH FROM new_cur2 INTO @myid, @name
While @@FETCH_STATUS = 0
BEGIN
IF PATINDEX ('@name%',@pdesc) = 0
Set @ssc = @myid
UPDATE C2000HPB
SET SubSubCatID = @ssc
FETCH NEXT FROM new_cur2 INTO @myid, @name
END
Close new_cur2
DEALLOCATE new_Cur2
FETCH NEXT FROM new_cur INTO @pdesc,@ssc
END
Close new_cur
DEALLOCATE new_Cur
View Complete Forum Thread with Replies
Related Forum Messages:
How Can I Assign A Stored Procedure As Cursor's Data Source In AStored Procedure?
How can I create a Cursor into a Stored Procedure, with another Stored Procedure as data source? Something like this: CREATE PROCEDURE TestHardDisk AS BEGIN DECLARE CURSOR HardDisk_Cursor FOR Exec xp_FixedDrives -- The cursor needs a SELECT Statement and no accepts an Stored Procedure as Data Source OPEN CURSOR HardDisk_Cursor FETCH NEXT FROM HardDisk_Cursor INTO @Drive, @Space WHILE @@FETCH_STATUS = 0 BEGIN ... END END
View Replies !
Cursor With Stored Procedure
I have a stored procedure that basically recieves the where clause of a select statement and executes the new sql statement... ie: CREATE PROCEDURE [dbo].[bsa_GetImportIDs] (@FilterText varchar(1000)) AS DECLARE @MySQL varchar(1000) SET @MySQL = "SELECT Import_ID FROM tblImport WHERE " + @FilterText EXEC (@MySQL) GO Now, in another stored procedure, I need to use the stored procedure above in a cursor so that I can execute an insert statement for each occurance of the Import_ID that appears in that dataset... ie: CREATE PROCEDURE [dbo].[bsa_PutLargeCase] AS DECLARE @CaseID uniqueidentifier SET @CaseID = NewID() Declare @ImportID uniqueidentifier Declare curClient Cursor FAST_FORWARD for SELECT Import_ID FROM dbo.bsa_GetImportIDs (@FilterText) <---- this does not work!!! Open curClient FETCH NEXT FROM curClient INTO @ImportID WHILE @@FETCH_STATUS = 0 BEGIN EXEC dbo.bsa_PutCaseDetail @CaseID, @ImportID FETCH NEXT FROM curClient INTO @ImportID END CLOSE curClient DEALLOCATE curClient GO How can I utilize my first stored procedure in the cursor of the second? ... or Are there any other approaches that may be a better solution to what I am trying to accomplish? Thanks in advance for any input.
View Replies !
Stored Procedure Into A Cursor
Hi guys!!I am trying to fill a cursor with the results of a StoredProcedured, but SQL give me an syntax error message , does any one cangive me some helpI am using SQL Server, this is the first lines of my codeDECLARE FRates_Cursor CURSOR FORexec GET_FJRs_Eng 'all'OPEN FRates_Cursorif I run just the exec GET_FJRs_Eng 'all' line it give me the dataresults I am trying to put into the cursor, what that means is thestored is working fineThanks in advance
View Replies !
Help In Stored Procedure With Cursor
I am trying to create the procedure from two tables to create the flat file from the two tables and as they are processed to the file then want to change the status from 'U' to 'P'. I am trying to declare the cursor from the union of two tables so that I can store the data into one table. And then put the data into the flat file and then marked the processed data as 'P' from 'U' please help in doing that. thanks, Harish CREATE PROCEDURE SP_P8 AS declare c123 cursor for select 'CA'+'|'+COMPANY+'|'+COMPANYNAME+'|'+CUSTOMERNUMBE R+'|'+COMPANYPHONE +'|'+COMPANYFAX+'|'+FEDTAXID+'|'+DUNSNUMBER+'|'+S1 099+'|'+DUNSSUFFIX+'|'+convert(char,ADDRESSSEQ) +'|'+COUNTRY+'|'+ADDRESSTYPE+'|'+ADDRESS1+'|'+ADDR ESS2+'|'+ADDRESS3+'|'+ADDRESS4 +'|'+CITY+'|'+STATE+'|'+ZIP+'|'+FAXNUMBER hello1,status from v1 UNION select 'CT'+'|'+COMPANY+'|'+CONTACTNAME+'|'+CONTACTTYPE+' |'+CONVERT(CHAR(10),CONTACTADDRESS) +'|'+PHONE+'|'+FAX+'|'+TITLE hello,status from v3 declare @status char(1) declare @wholerecord text open c123 fetch next from c123 into @wholerecord,@status while @@fetch_status=0 begin update v1 set status='P' where current of c123 update v3 set status='P' where current of c123 fetch next from c123 into @wholerecord,@status end close c123 deallocate c123 select * into temp23 from v2 where status='P' and declare @v datetime declare @filename varchar(32) select @v=getdate() select @filename = 'XCUST'+CONVERT(varchar, @v, 112)+ SUBSTRING(CONVERT(varchar, @v, 108), 1, 2) + SUBSTRING(CONVERT(varchar, @v, 108), 4, 2)+ SUBSTRING(CONVERT(varchar, @v, 108), 7, 2) + '.TXT' declare @cmdstring varchar(255) Select @cmdstring = 'bcp conversion..temp23 out d:est' + @filename + ' -c -t"|" -r -S -Usa -Ppassword' exec master..xp_cmdshell @cmdstring drop table temp23
View Replies !
Help In Stored Procedure With Cursor
Please help in creating the stored procedure for the following code. Thanks in Advance. ============================= Create procedure extractdata @companynumber varchar(3), @firstdateofmonth int, @lastdateofmonth int as truncate table xt truncate table xtt insert into xt(account_code,balance_date,net_change,current_ba lance,oldlob) select account_code, balance_date,net_change,current_balance,@companynu mber from ccc@companynumber..glbal where balance_date<=@firstdateofmonth declare @v1 varchar(32) declare @v2 int declare @v3 float declare c1 cursor for select account_code, max(balance_date) from xt where oldlob=@companynumber group by account_code open c1 fetch next from c1 into @v1,@v2 WHILE @@FETCH_STATUS = 0 begin update xt set status='max' where account_code=@v1 and balance_date=@v2 and oldlob=@companynumber fetch next from c1 into @v1,@v2 end close c1 deallocate c1 insert into xtt(account_code,balance_date,net_change,current_b alance,oldlob) select account_code,balance_date,net_change,current_balan ce,oldlob from xt where status='max' and oldlob=@companynumber order by account_code insert into test1(account_code,current_balance,net_change,bala nce_date,oldlob) select account_code,round(current_balance,2),round(net_ch ange,2),balance_date,@companynumber from xtt where oldlob=@companynumber and account_code in (select account_code from xxxmay where oldlob=@companynumber) update test1 set net_change=0 where balance_date<@lastdateofmonth and oldlob=@companynumber select sum(current_balance),sum(net_change) from test1 where oldlob=@companynumber
View Replies !
Out A Cursor From A Stored Procedure
hello! any of you have an idea how i can declare an output parameter for my cursor which is inside a stored procedure. i would lik to see the output using the exec command but i don't know how to get the out from my cursor. please help! honey
View Replies !
Using Cursor As OUT Parameter In Stored Procedure
Hi guys, I have a serious problem. I need to use my cursor as an out parameter, but the problem is, HOW CAN I CLOSE THE CURSOR??????If I dont close the cursor, my server is getting really slow because of the open cursors, cause I have more than 100 stored procedures, which have a cursor as an out-parameter.Here's one of my stored procedures : create or replace PACKAGE pkgResIS TYPE resType IS REF CURSOR RETURN res%ROWTYPE;END pkgRes; create or replace procedure res_sel_val(p_id in number,cs out pkgRes.resType)asBEGIN open cs for select * from res where res_id = p_id; --close cs;EXCEPTION when others then raise_application_error(-20970, 'record kan niet geselecteerd worden');END res_sel_val; How can I close my cursor? If I write the "close cursor" (which is in red at the code above), it returns an empty cursor, which is not my intention.Please help me with thisThanks in advance Morph 'n Nike
View Replies !
Creating Cursor From Stored Procedure
Hi guys!i want to create one cursor in the t-sql. the problem is i want to usestored procedure instead of select command in cursor.can anyone tell me how can i use stored procedure's o/p to createcursor?i'm using sql 2000 and .net 2.0thanks,Lucky
View Replies !
Error From Stored Procedure With A Cursor
I receive the following intermittent error when executing a stored procedure: Msg 16942, Sev 16: Could not generate asynchronous keyset. The cursor has been deallocated. [SQLSTATE 42000] Msg 3624, Sev 16: Location: lckclass.cpp:111 Expression: m_status == ACTIVE || m_status == ORPHANED SPID: 17 Process ID: 203 [SQLSTATE 01000] The process uses a cursor to update a SQL7 table from another. This is not a consistent failure. Sometimes the procedure runs fine to completion. Has anyone else had the same problem??? We had a suggestion that it might be a tempdb problem??? Any ideas?
View Replies !
Dynamic Cursor In Stored Procedure
when i try to compile the following sp, i get an error Line 11:Incorrect syntax near;. Can someone please tell me what i am doing wrong. thanks a lot. CREATE PROCEDURE test_dump (@p_query nvarchar(4000)) AS declare @cmdtxt as varchar(4000), @SQLString NVARCHAR(4000), @SQLString1 NVARCHAR(4000), @pid varchar(22), @lname varchar(60) begin EXEC SQL BEGIN DECLARE SECTION; char prep[] = @p_query; EXEC SQL END DECLARE SECTION; EXEC SQL PREPARE prep_stat FROM :prep; EXEC SQL DECLARE contact_crsr CURSOR FOR prep_stat; OPEN contact_crsr FETCH NEXT FROM contact_crsr INTO @pid, @lname -- Check @@FETCH_STATUS to see if there are any more rows to fetch. WHILE @@FETCH_STATUS = 0 BEGIN SET @SQLString1 = 'HELLO ' + @pid + ' ' + @lname select @cmdtxt = "echo " + @SQLString1 + " >> c:empmyfile.txt" exec master..xp_cmdshell @cmdtxt FETCH NEXT FROM contact_crsr INTO @pid, @lname END CLOSE contact_crsr DEALLOCATE contact_crsr end
View Replies !
How To Declare Cursor In Stored Procedure?
I am trying to decalare the cursor in the below stored procedure. Can any one please help me to correct the cursor declaration?? Basically, i am testing how to declare the cursor in stored procedure. CREATE PROCEDURE STP_EMPSAL @empno int, @Employee_Cursor CURSOR VARYING OUTPUT FOR SELECT empno FROM AdventureworksDW.dbo.emp AS OPEN Employee_Cursor; FETCH NEXT FROM Employee_Cursor into @empno; WHILE @@FETCH_STATUS = 0 BEGIN BEGIN TRAN UPDATE emp set sal= sal+ 2000 where empno = @empno and comm is null mgr='Scott'; FETCH NEXT FROM Employee_Cursor into @empno; COMMIT; END; CLOSE Employee_Cursor; DEALLOCATE Employee_Cursor;
View Replies !
Stored Procedure Using A Declared Cursor
I need to write a stored procedure using T-SQL to declare a cursor for containing id(staff_no), names and specialism of all doctors that have specialism, The contents of the cursor then are to be displayed using a loop and print statement to give a formatted display of the output of each record within the cursor. The doctors table has the following columns with specialism allowing NULL values doctor ( staff_no CHAR(3), doctor_name CHAR(12), position CHAR(15), specialism CHAR(15), PRIMARY KEY(staff_no) ) Any help would be greatly appreciated.
View Replies !
Sql Stored Procedure - With In Cursor Get @@identity Value For Insert And Use That Again
I have stored procedure which contains follwing part of it. it says syntax when i worte line to get @@identity valuewhen delete that line command succesful. but i need to get @@identity from the insert statement and assign it to a variable and use it after any body pls tell me how to get this within a stored prosedure or what is the error of the following code bit. (#tblSalesOrders is a temporary table which containsset of records from orginal table )DECLARE @soNo1 INT DECLARE @CursorOrders CURSOR SET @CursorOrders = CURSOR FAST_FORWARD FOR select fldSoNo from #tblSalesOrders declare @newSONO1 int OPEN @CursorOrders FETCH NEXT FROM @CursorOrders INTO @soNo1 WHILE @@FETCH_STATUS = 0 BEGIN ----for each salesorder insert to salesorderline insert into tblSalesOrders (fldWebAccountNo,fldDescription,fldSoDate,fldGenStatus) select (fldWebAccountNo,fldDescription,fldSoDate,fldGenStatus) from #tblSalesOrders where fldSoNo =@soNo1; set @newSONO1=SCOPE_IDENTITY; -------in this section again create another cursor for another set of records and insert to a table passing identity value return from the above insert -------------------------- SELECT @intErrorCode = @@ERRORIF (@intErrorCode <> 0) GOTO PROBLEM FETCH NEXT FROM @CursorOrders INTO @soNo1 END CLOSE @CursorOrders DEALLOCATE @CursorOrders
View Replies !
Receiving And Sending A Cursor With(in) A Stored Procedure
Can someone post some code that shows a Stored Procedure receiving a cursor that it can process - lets say a group of order detail records are received that must be saved along with the single Order header record. And, in another example, a SP returns a result set to the calling program. - For example, a particular sale receipt is pulled up on the screen and the order detail is needed. Thanks for help on this, Peter
View Replies !
Unique Cursor Name In Recursive Stored Procedure
How can I solve this probleM? I thing that I need to create cursor with unique cursor name procedure XX param DECLARE cc CURSOR FOR SELECT....param --ERROR bcause it's already exists OPEN cc ... WHILE @@FETCH_STATUS = 0 BEGIN XX param FETCH NEXT ... END CLOSE cc ....
View Replies !
Make A Dynamic Cursor In A Stored Procedure
I need im my aplication to meke a "Cursor" in a execution of a stored procedure. For sample: In a table with a report definition I have the "Fileds, From, Group, Order " clausulas and I need make a cursor with a contents of this fileds. How can I do ??? My code: Declare @idRelat int, @cmd_FROM nvarchar(1024), @cmd_Det nvarchar(50) SELECT @idRelat = idRelat, @cmd_Det = cmd_DET FROM Relatórios WHERE Nome = @p_Relat Declare @Tot_Col smallint, @Tot_Lin smallint, @Campos smallint, @Aux_Select nvarchar(1024), @Aux_Group nvarchar(1024), @Aux_Order nvarchar(1024) Select @Tot_Col = 0 Select @Tot_Lin = 0 Select @Campos = 0 Select @Aux_Select = "SELECT " + @cmd_DET + "AS Soma" Select @Aux_Group = "GROUP BY " Select @Aux_Order = "ORDER BY " Declare @a_Local char(1), @a_Linha smallint, @a_Campo nvarchar(50) Declare cur_Aux insensitive cursor for SELECT Local, Linha, Campo From Relatórios_Margens WHERE (idRelat = @idRelat) ORDER BY Local, Linha Open cur_Aux Fetch cur_Aux into @a_Local, @a_Linha, @a_Campo While @@FETCH_status = 0 begin If @a_Local = "C" Select @Tot_Col = @Tot_Col + 1 Else Select @Tot_Lin = @Tot_Lin + 1 Select @Campos = @Campos + 1 If @Aux_Group <> "GROUP BY " begin Select @Aux_Group = @Aux_Group + ", " If @Aux_Order <> "ORDER BY " begin Select @Aux_Order = @Aux_Order + ", " Select @Aux_Select = sSelect + ", " + @a_Campo + " AS Campo" + @Campos Select @Aux_Group = @Aux_Group + @a_Campo Select @Aux_Order = @Aux_Order + @a_Campo Fetch cur_Aux into @a_Local, @a_Linha, @a_Campo End Select @Aux_Select = @Aux_Select -- <<<< MONTA COMANDO SQL Select @Aux_Select = @Aux_Select + " " + @cmd_FROM + " " + @p_Filtro + " " + @Aux_Group + " " + @Aux_Order Declare @Cursor_Aux cursor Set @Cursor_Aux = cursor for @Aux_Select Open @Cursor_Aux Not working !!!!
View Replies !
How To Call A Stored Procedure In T-SQL And Pass It To A Cursor
Hi, I have a kind of problem. In SQL Server I have a stored procedure ressembling this: Code Block ALTER PROCEDURE procedure1 ( @param int ) SELECT * FROM table WHERE param = @param Now I want to call this procedure and pass it to a cursor. We all know you can do this: Code Block DELCARE cursor1 CURSOR for SELECT * FROM table WHERE param = @param .. , but I want something like this: Code Block DECLARE cursor1 CURSOR for EXEC procedure1 @param Is it possible? I could solve it in another, but then I have to connect 2x to the database, which is less performant. I have also tried something like this: Code Block ALTER PROCEDURE procedure1 ( @param int ) SELECT @test = id FROM table WHERE param = @param RETURN @test ALTER PROCEDURE procedure2 ( @param int ) DECLARE @var varchar(100) EXEC @var = procedure1 @param But then it returns always 0. So is there a way to pass a procedure's select to a cursor? Thanks in advance Stevevil0
View Replies !
Problem When Invoking Stored Procedure With Cursor From Inside .net
Dear all,i'm facing a problem with my storedprocedure which happened when i ran my web application and reach to the point where my class invoke this storedprocedure,my SP contains a cursor that built his sql according to certain condition, so i put the "SET @cur Cursor For....." inside the if block (definitely i've declared it under AS keyword directly) and this SP is working well inside sql server(I've tested it), BUT when my ASP.net code invoke this SP it gives me the following error : "The Variable @cur does not currently have a cursor allocated to it" repeated as much as there are IF clauses in my SP,Please Help.Regards,
View Replies !
Cursor Works In Query Analyzer But Not In Stored Procedure
Hi i have a script works in sql query analyzer; declare @id decimal declare mycur CURSOR SCROLL for select myRowID from myTable order by myRowID open mycur; Fetch ABSOLUTE 30 from mycur into @id close mycur; deallocate mycur; select @id this script turns me a value. i create a stored procedure from above script and its syntax is ok; CREATE PROCEDURE SELECT_MyRow AS declare @cur cursor declare @RowID decimal set @cur = CURSOR SCROLL for select myRowID from myTable order by myRowID open @cur Fetch ABSOLUTE 30 from @cur into @RowID close @cur deallocate @cur select @RowID GO my c# code using stored procedure is below; Code Snippet try { OleDbCommand cmd = new OleDbCommand("SELECT_MyRow", myconnection); cmd.CommandType = CommandType.StoredProcedure; myconnection.Open(); OleDbDataReader reader = cmd.ExecuteReader(); MessageBox.Show(reader.GetName(0));//here fails while (reader.Read()) { MessageBox.Show(reader.GetDecimal(0).ToString()); } reader.Close(); myconnection.Close(); } catch(Exception ex) { MessageBox.Show(ex.Message); } The code above fails because reader reads no values, error message is "No data exists for the row/column" but i know exists. Can anyone help me, what is the difference between stored procedure and script ?
View Replies !
Stored Procedure With CURSOR OUTPUT Parameter, Using JDBC And A Callable Statement
My server is MS Sql Server 2005. I'm using com.microsoft.sqlserver.jdbc.SQLServerDriver as the driver class. I've established a connection to the database. I'm trying to invoke a stored procedure using JDBC and a callable statement. The stored procedure has a parameter @CurOut CURSOR VARYING OUTPUT. How do I setup the callable statement so the output parameter is accepted by the driver? I'm not really trying to pass a cursor up to the database Server but I'm wanting a cursor back from the stored procedure that is other than the result set or other value the stored procedure returns. First problem: What java.sql.Types (or SQL Server specific) value do I specify for the out parameter I'm registering on the CallableStatement? Second problem: What do I set the value of the parameter to? The code looks like: CallableStatement cstmt = myConnection.prepareCall(sQuery); cstmt.registerOutParameter(1, Types.OTHER); // What is the right type? cstmt.setNull(1, Types.OTHER); // What is the right type? if (cstmt.execute()) { ResultSet rs = cstmt.getResultSet(); } Execution results in a NullPointerException from the driver. What am I doing wrong? Thanks for your assistance. Jon Weaver
View Replies !
URGENT Help --------- Stored Procedure
Hi !! We are in a situaltion.... and don't have any answer... We have 3 stored procedure. We want to write output of all the 3 stored procedure into one text file.. How do we do this? We thought about DTS but its not solving our problem...
View Replies !
Stored Procedure (Urgent)
I need to display the records from a start record number to an end record number. I need a stored procedure for this. The procedure should accept the query, start record number and the end record number as parameters. The procedure should be optimized such that it would work fast with even 1 lac records or more in the database table. Please help.....
View Replies !
How To Use The Return Value Of A Stored Procedure (URGENT)
Hi everyone, I have a stored procedure as the following:1 ALTER PROCEDURE dbo.logincheck2 @ID int,3 @Password varchar(50),4 @Result int output5 AS6 IF EXISTS (SELECT * FROM users WHERE (ID=@ID AND Password=@Password))7 BEGIN8 SET @Result=19 END10 11 ELSE12 BEGIN13 SET @Result=014 END15 16 RETURN @Result What I'm trying to do is using @result in my login.aspx.vb to check if user exists in my database. If he is, the result should be 1 and if not it should be 0. Unfortunately, I don't know how to do it. I must submit my project in 2 days and I'm desperately seeking for help. Here is my code: 1 Dim sqlcon As New SqlClient.SqlConnection2 Dim sqlcmd As New SqlCommand()3 Dim sonuc As Integer = 04 If IsValid Then5 sqlcon.ConnectionString = "Data Source=.SQLEXPRESS;AttachDbFilename=C:UsersShadow ShooterWebSiteMainProjectApp_Datamydb.mdf;Integrated Security=True;User Instance=True"6 sqlcon.Open()7 sqlcmd.Connection = sqlcon8 sqlcmd.CommandType = CommandType.StoredProcedure9 sqlcmd.CommandText = "logincheck"10 sqlcmd.Parameters.Add("@ID", SqlDbType.Int, 4, "ID")11 sqlcmd.Parameters("@ID").Value = txtUsername.Text12 13 sqlcmd.Parameters.Add("@Password", SqlDbType.VarChar, 50, "Password")14 sqlcmd.Parameters("@Password").Value = txtPassword.Text15 16 sqlcmd.Parameters.Add("@Result", SqlDbType.Int, 4, sonuc)17 sqlcmd.Parameters("@Result").Direction = ParameterDirection.Output18 19 20 sqlcmd.ExecuteNonQuery()21 22 If (sonuc = 1) Then23 24 Response.Write("USER FOUND :)")25 'cookie is set with SESSION ID.26 Response.Cookies("User").Value = Session.SessionID27 Response.Cookies("user").Expires = DateTime.Now.AddMinutes(30)28 'Response.Redirect("Welcome.aspx")29 Else30 Response.Write("USER NOT FOUND :(")31 'Response.Redirect("invalid.aspx")32 33 End If
View Replies !
Passing A Value To Another Stored Procedure...need Urgent Help
Hi i have been working on these stored procedures for what seems like ages now and i just cant understand why they dont work. I have followed many tutorials and think i have the correct synat but i jus keep getting errors. Basically, i have SPOne and SPTwo - SPOne is writing to a table called Publication that has PublicationID as its PK (auto generated). SPtwo needs to get this PublicationID from SPOne and use it to insert rows into a second table PublicationAuthors - the PublicationID is hence a FK in the table PublicationAuthors. The error i get is: Procedure or function 'SPOne' expects parameter '@publicationID', which was not supplied. Cannot insert the value NULL into column 'publicationID', table .dbo.PublicationAuthors'; column does not allow nulls. INSERT fails. SPOne is as follows: ALTER PROCEDURE dbo.StoredProcedureOne @typeID smallint=null, @title nvarchar(MAX)=null, @publicationID smallint OUTPUTASBEGIN SET NOCOUNT ON INSERT INTO Publication (typeID, title) VALUES (@typeID, @title) SELECT @publicationID = scope_identity() END and SPtwo is as follows: ASDECLARE @NewpublicationID IntEXEC StoredProcedureOne @NewpublicationID = OUTPUTSET @publicationID = @NewpublicationIDINSERT INTO PublicationAuthors (publicationID, authorID) VALUES (@publicationID, @authorID) SELECT @NewpublicationID Thanks Gemma
View Replies !
Stored Procedure Debugger Help!(URGENT)
Hi.Can any one tell me how to configure the settings in ms sql server 2000 (query analyzer) to enable the store procedure to be debug.I receive an error message some such"SP debugging may not work properly if u log on as "local system account" while sql server is configured to run as service"Any help is appreciated.Thank you
View Replies !
URGENT Remote Stored Procedure
Hi I have suddenly lost the ability to run the following LIVE TSQL statement: EXEC SQL.HTN.dbo.sp_StoredProcedure Yet, this works fine: Select * from OPENQUERY(SQL, 'sp_StoredProcedure') I cannot see anything wrong with the linked server. The error message is as follows: Server: Msg 7201, Level 17, State 4, Line 1 Could not execute procedure on remote server 'SQL' because SQL Server is not configured for remote access. Ask your system administrator to reconfigure SQL Server to allow remote access. Can someone please point me in the right direction to the problem... and the solution Thanks in advance Graham
View Replies !
Sql Stored Procedure Problem(very Urgent)
Since i am newbie to sqlserver and & stored procedure. I need some help to modify the existing stored procedure. The values and parameters are passing to stored procedure from Asp page. My question is in Stored procedure, there is one value is Company name (vchCompany Name) , I need to check the values passed from the asp page, whether the company name is already exists in the table. If exists display the pop up message window. Thanks The code is below: ************************************************** **** CREATE procedure wbospsiCompany @iSiteId int, @iCompanyId int = NULL OUTPUT, @chLanguageCode char(4), @vchAssignedId varchar(255), @vchCompanyName varchar(255), @vchAddress1 varchar(255), @vchAddress2 varchar(255), @vchAddress3 varchar(255), @vchCity varchar(255), @chRegionCode char(4), @chCountryCode char(4), @vchPostCode varchar(40), @vchPhoneNumber varchar(40), @vchEmailAddress varchar(255), @vchURL varchar(255), @iCompanyTypeCode int, @iCompanySubTypeCode int, @iFamilyId int, @iParentId int, @iPrimaryContactId int, @vchContactFirstName varchar(255), @vchContactLastName varchar(255), @iDivisionCode int, @iSICCode int, @iMarketSector int, @vchTaxId varchar(255), @vchDunnsNumber varchar(255), @iPhoneTypeId int, @iAddressTypeId int, @iSourceId int, @iStatusId int, @bValidAddress tinyint, @iAccessCode int, @bPrivate tinyint, @vchUser1 varchar(255) = NULL, @vchUser2 varchar(255) = NULL, @vchUser3 varchar(255) = NULL, @vchUser4 varchar(255) = NULL, @vchUser5 varchar(255) = NULL, @vchUser6 varchar(255) = NULL, @vchUser7 varchar(255) = NULL, @vchUser8 varchar(255) = NULL, @vchUser9 varchar(255) = NULL, @vchUser10 varchar(255) = NULL, @chInsertBy char(10) = NULL, @dtInsertDate datetime = NULL, @tiLockRecord tinyint = 0, @tiRecordStatus tinyint = 1, @tiReturnType tinyint = 1 AS /* ** ObjectName: wbospsiCompany ** ** Project: Apollo ** SubProject: ** FileName: Insert.sql ** Type: Production ** ** Description: Inserts a record into the Company table. ** ** Valid Values for @tiLockRecord Valid Values for @tiReturnType ** ------------------------------ ------------------------------ ** 1 = Lock Record 1 = Result Set ** 0 = Don't Lock Record 0 = Output Only ** ** Revision History ** ---------------------------------------------------------------------------- ** Date Name Description ** ---------------------------------------------------------------------------- ** 1/26/99 RobertA Created ** 10/11/99 GregP Dion schema compatibility changes ** */ BEGIN /* ** Declare & initialize Local Variables */ declare @iReturnCode int, @iWBOCPExists int, @iWBOCPReturn int select @iReturnCode = 0, @iWBOCPExists = 0, @iWBOCPReturn = 0 /* ** Declare & initialize Local Constants */ declare @PRE_OPTION int, @CORE_OPTION int, @POST_OPTION int, @INSERT_CODE char(1), @chUpdateBy char(4), @dtUpdateDate datetime, @dtModifiedDate datetime select @PRE_OPTION = 0, @CORE_OPTION = 0, @POST_OPTION = @tiLockRecord * 2, /* Lock if @tiLockRecord = 1 */ @INSERT_CODE = "I", @chUpdateBy = NULL, @dtUpdateDate = NULL, @dtModifiedDate = NULL exec @iReturnCode = ospsiCompanyPre @iSiteId OUTPUT, @iCompanyId OUTPUT, @chLanguageCode OUTPUT, @vchAssignedId OUTPUT, @vchCompanyName OUTPUT, @vchAddress1 OUTPUT, @vchAddress2 OUTPUT, @vchAddress3 OUTPUT, @vchCity OUTPUT, @chRegionCode OUTPUT, @chCountryCode OUTPUT, @vchPostCode OUTPUT, @vchPhoneNumber OUTPUT, @vchEmailAddress OUTPUT, @vchURL OUTPUT, @iCompanyTypeCode OUTPUT, @iCompanySubTypeCode OUTPUT, @iFamilyId OUTPUT, @iParentId OUTPUT, @iPrimaryContactId OUTPUT, @vchContactFirstName OUTPUT, @vchContactLastName OUTPUT, @iDivisionCode OUTPUT, @iSICCode OUTPUT, @iMarketSector OUTPUT, @vchTaxId OUTPUT, @vchDunnsNumber OUTPUT, @iPhoneTypeId OUTPUT, @iAddressTypeId OUTPUT, @iSourceId OUTPUT, @iStatusId OUTPUT, @bValidAddress OUTPUT, @iAccessCode OUTPUT, @bPrivate OUTPUT, @vchUser1 OUTPUT, @vchUser2 OUTPUT, @vchUser3 OUTPUT, @vchUser4 OUTPUT, @vchUser5 OUTPUT, @vchUser6 OUTPUT, @vchUser7 OUTPUT, @vchUser8 OUTPUT, @vchUser9 OUTPUT, @vchUser10 OUTPUT, @chInsertBy OUTPUT, @dtInsertDate OUTPUT, @chUpdateBy, @dtUpdateDate, @tiRecordStatus OUTPUT, @dtModifiedDate, @PRE_OPTION if @iReturnCode <> 0 begin exec @iReturnCode = ospCheckError "p", @iReturnCode end /* ** Determine if @vchAssignedId and @iIndividualId should be set by configs */ if @iReturnCode <= 0 begin exec @iReturnCode = ospsuCustomerIds @iSiteId, "Company", @chCountryCode, @iCompanyId OUTPUT, @vchAssignedId OUTPUT if @iReturnCode <> 0 begin exec @iReturnCode = ospCheckError "p", @iReturnCode end end /* ** Determine if WBOCP configurable procedure exists */ exec @iWBOCPExists = ospObjectExists "wbocpscCompany", "p" if @iReturnCode <= 0 begin begin transaction if @iWBOCPExists = 1 begin exec @iWBOCPReturn = wbocpscCompany @INSERT_CODE, @iSiteId, @iCompanyId, @chLanguageCode OUTPUT, @vchAssignedId OUTPUT, @vchCompanyName OUTPUT, @vchAddress1 OUTPUT, @vchAddress2 OUTPUT, @vchAddress3 OUTPUT, @vchCity OUTPUT, @chRegionCode OUTPUT, @chCountryCode OUTPUT, @vchPostCode OUTPUT, @vchPhoneNumber OUTPUT, @vchEmailAddress OUTPUT, @vchURL OUTPUT, @iCompanyTypeCode OUTPUT, @iCompanySubTypeCode OUTPUT, @iFamilyId OUTPUT, @iParentId OUTPUT, @iPrimaryContactId OUTPUT, @vchContactFirstName OUTPUT, @vchContactLastName OUTPUT, @iDivisionCode OUTPUT, @iSICCode OUTPUT, @iMarketSector OUTPUT, @vchTaxId OUTPUT, @vchDunnsNumber OUTPUT, @iPhoneTypeId OUTPUT, @iAddressTypeId OUTPUT, @iSourceId OUTPUT, @iStatusId OUTPUT, @bValidAddress OUTPUT, @iAccessCode OUTPUT, @bPrivate OUTPUT, @vchUser1 OUTPUT, @vchUser2 OUTPUT, @vchUser3 OUTPUT, @vchUser4 OUTPUT, @vchUser5 OUTPUT, @vchUser6 OUTPUT, @vchUser7 OUTPUT, @vchUser8 OUTPUT, @vchUser9 OUTPUT, @vchUser10 OUTPUT, @chInsertBy OUTPUT, @dtInsertDate OUTPUT if @iWBOCPReturn <> 0 begin exec @iReturnCode = ospCheckError "p", @iWBOCPReturn end if @iReturnCode <= 0 begin exec @iReturnCode = espcpCheckCustomerId @iSiteId, @iCompanyId end end if @iReturnCode <= 0 begin exec @iReturnCode = ospsiCompanyCore @iSiteId, @iCompanyId, @chLanguageCode OUTPUT, @vchAssignedId OUTPUT, @vchCompanyName OUTPUT, @vchAddress1 OUTPUT, @vchAddress2 OUTPUT, @vchAddress3 OUTPUT, @vchCity OUTPUT, @chRegionCode OUTPUT, @chCountryCode OUTPUT, @vchPostCode OUTPUT, @vchPhoneNumber OUTPUT, @vchEmailAddress OUTPUT, @vchURL OUTPUT, @iCompanyTypeCode OUTPUT, @iCompanySubTypeCode OUTPUT, @iFamilyId OUTPUT, @iParentId OUTPUT, @iPrimaryContactId OUTPUT, @vchContactFirstName OUTPUT, @vchContactLastName OUTPUT, @iDivisionCode OUTPUT, @iSICCode OUTPUT, @iMarketSector OUTPUT, @vchTaxId OUTPUT, @vchDunnsNumber OUTPUT, @iPhoneTypeId OUTPUT, @iAddressTypeId OUTPUT, @iSourceId OUTPUT, @iStatusId OUTPUT, @bValidAddress OUTPUT, @iAccessCode OUTPUT, @bPrivate OUTPUT, @vchUser1 OUTPUT, @vchUser2 OUTPUT, @vchUser3 OUTPUT, @vchUser4 OUTPUT, @vchUser5 OUTPUT, @vchUser6 OUTPUT, @vchUser7 OUTPUT, @vchUser8 OUTPUT, @vchUser9 OUTPUT, @vchUser10 OUTPUT, @chInsertBy OUTPUT, @dtInsertDate OUTPUT, @chUpdateBy, @dtUpdateDate, @tiRecordStatus OUTPUT, @dtModifiedDate, @CORE_OPTION if @iReturnCode <> 0 begin exec @iReturnCode = ospCheckError "p", @iReturnCode end end /* ** Transaction Management */ if @iReturnCode <=0 begin commit transaction end else begin rollback transaction end if @iReturnCode <= 0 begin /* ** Call post procedure */ exec @iReturnCode = ospsiCompanyPost @iSiteId, @iCompanyId, @chLanguageCode OUTPUT, @vchAssignedId OUTPUT, @vchCompanyName OUTPUT, @vchAddress1 OUTPUT, @vchAddress2 OUTPUT, @vchAddress3 OUTPUT, @vchCity OUTPUT, @chRegionCode OUTPUT, @chCountryCode OUTPUT, @vchPostCode OUTPUT, @vchPhoneNumber OUTPUT, @vchEmailAddress OUTPUT, @vchURL OUTPUT, @iCompanyTypeCode OUTPUT, @iCompanySubTypeCode OUTPUT, @iFamilyId OUTPUT, @iParentId OUTPUT, @iPrimaryContactId OUTPUT, @vchContactFirstName OUTPUT, @vchContactLastName OUTPUT, @iDivisionCode OUTPUT, @iSICCode OUTPUT, @iMarketSector OUTPUT, @vchTaxId OUTPUT, @vchDunnsNumber OUTPUT, @iPhoneTypeId OUTPUT, @iAddressTypeId OUTPUT, @iSourceId OUTPUT, @iStatusId OUTPUT, @bValidAddress OUTPUT, @iAccessCode OUTPUT, @bPrivate OUTPUT, @vchUser1 OUTPUT, @vchUser2 OUTPUT, @vchUser3 OUTPUT, @vchUser4 OUTPUT, @vchUser5 OUTPUT, @vchUser6 OUTPUT, @vchUser7 OUTPUT, @vchUser8 OUTPUT, @vchUser9 OUTPUT, @vchUser10 OUTPUT, @chInsertBy OUTPUT, @dtInsertDate OUTPUT, @chUpdateBy, @dtUpdateDate, @tiRecordStatus OUTPUT, @dtModifiedDate, @POST_OPTION if @iReturnCode <> 0 begin exec @iReturnCode = ospCheckError "p", @iReturnCode end end end /* ** Manage return: return ID of record based upon @ReturnType param */ exec @iReturnCOde = ospManageReturn @tiReturnType, @iReturnCode, @iSiteID, @iCompanyId, "Company", "I" if @iReturnCode = 0 begin select @iReturnCode = @iWBOCPReturn end return @iReturnCode END ************************************************** ****
View Replies !
Urgent! Asp And Sql Stored Procedure Parameters
Hi, I have a problem with input parameter which has Decimal DataType. Stored procedure works but it rounds all values, i.e 5.555 input becomes 6 and 1.3 input becomes 1. In table QTY has data type decimal(5) - precision(8) scale(3). Please, suggest what's wrong with this: newqty = Request.Form("quantity") .......... cmd.Parameters.Append(cmd.CreateParameter("qty", adDecimal, adParamInput, 5, newqty)) cmd.Parameters("qty").Precision = 8 cmd.Parameters("qty").NumericScale = 3 Please, help! Thanks in advance.
View Replies !
How To Pass XML File To Stored Procedure (Urgent)
i am trying to pass a large XML file from VS2005 (web service layer) to stored procedure (SQL Server 2000)In my stored procedure, the input parameter takes as "nText" (which will be XML file)Question:While performing ExecuteNonQuery, i am getting request timeout i think this is coz of large XML file i am passing.can anyone plz tell me how to pass XML file to SP...it would be better if you can provide me with some codei am completely new to this XML file passing between web service and SP...... thanks a lot in advance.....
View Replies !
Insertion Data Via Stored Procedure [URGENT]!!
Hi all; Question: ======= Q1) How can I insert a record into a table "Parent Table" and get its ID (its PK) (which is an Identity "Auto count" column) via one Stored Procedure?? Q2) How can I insert a record into a table "Child Table" whose (FK) is the (PK) of the "Parent Table"!! via another one Stored Procedure?? Example: ------------ I have two tables "Customer" and "CustomerDetails".. SP1: should insert all "Customer" data and return the value of an Identity column (I will use it later in SP2). SP2: should insert all "CustomerDetials" data in the record whose ID (the returned value from SP1) is same as ID of the "Customer" table. FYI: ---- MS SQL Server 2000 VS.NET EA 2003 Win XP SP1a VB.NET/ASP.NET :) Thanks in advanced!
View Replies !
Urgent : Running A Script Sql From A Stored Procedure
Hi, I want to know what's the best way to run a script from a stored procedure. ??? I explain exactly what I want to do : I made a lot of stored procedures for SQL Server 7. Now I install Sql Server 2000 and i want to optimze the program. So before I run my SQL Server 7 procedures I want to add a procedure : if this is the SQL 2000 version it runs an upgrade script Thanks to your answers Axel
View Replies !
Stored Procedure In SELECT Statement?? Urgent
I have a stored procedure in an Informix-database that returns a string. Its used in a SELECT statement like this. SELECT t1.id, t2.id, sp_name(t1.id, t2.id) FROM table1 t1, table2 t2 I want to write it in SQLserver. I have tried this syntax but get error. Server: Msg 170, Level 15, State 1, Line 1 Line 1: Incorrect syntax near 't'. SELECT t1.id, t2.id, dbo.sp_name(t1.id, t2.id, "") FROM table1 t1, table2 t2 Can I use stored proc in this way in SQL-server?
View Replies !
Urgent: Whichj One Is Faster : SSIS Or Stored Procedure
Hi My PM and me are on a discussion. He wants SSIS to simply upload the source excel files in staging and do rest of the ETL in SQl server stored procedure which I feel is primitive. I have suggested him to use SSIS for whole ETL and not Stored procedure( method which indistry has discarded) He sayd Stored procedure are more efficient than SSIS. Please guide with some facts.
View Replies !
URGENT: Stored Procedure Throws Windows Error 203
I am trying to execute a stored procedure on Server1 which creates an excel report on a share of Server2: The following error message is thrown: Saving of scheduled report(s) to Excel file failed : 203 SaveReportToExcel() in TlRptToFile.RptExcel failed in sproc_SaveReportAsFile - TLRptXL::SaveReportToExcel - Connection to Database failed for Analytics DataBase Server : TKTALSQL3, Application Server: and DataBase : tlAnalytics : Windows Error - The system could not find the environment option that was entered. A DCOM component on Server1 runs the stored procedure that creates the excel report. The account under which DCOM component runs is a member of 'Administrators' group on both Server1 and Server2. Checked permissions on the shares. Account is a local Admin on both Server1 and Server2. Account under which SQLServer and ServerAgent runs is also an Admin on these shares (implicitly as part of 'Administrators' group). I am manually able to create an excel/text file on the Server2 share while accessing it from Server1, though. Appreciate your help in resolving the issue.
View Replies !
PRINT Debug Messages And CURSOR In Stored Procedure Confuses DTS; &"Invalid Pointer&"
I have the following stored procedure that is called from the source ofa transformation in a DTS package. The first parameter turns on PRINTdebug messages. The second, when equals 1, turns on the openning,fetching, and closing of a cursor. Things are fine if only one of thetwo parameters was set to 1.When run with both parameters turned on, "dba_test_dts 1, 1", DTSsource (tab) preview fails because it thinks no row was returned. "Norowset was returned from the SQL statement". Understanbly then thetransformation step would also fail with the "Invalid Pointer" error.As you'd see, I have SET NOCOUNT ON in the code. Has anyoneexperienced this? Is this a known bug? This occurs in SQL Server 2000running on Windows Server 2003.-----------------------------------------------------------------------------------------------------------------CREATE PROC dba_test_dts ( @debug BIT = NULL, @cur BIT = NULL )AS-- Always have these 2 options set or unset so DTS would not error out-- with the Invalid Pointers message.SET NOCOUNT ONSET ANSI_WARNINGS OFFDECLARE @FMT_FILE_NAME VARCHAR(256)DECLARE @OUTPUT_FILE_NAME VARCHAR(256)DECLARE @emp_id INTDECLARE @lastname VARCHAR(70)IF ( @debug = 1 )BEGINPRINT '=== BEGIN ==='PRINT 'Stored Procedure dts_calling_stored_proc'PRINT 'Begin timestamp: ' + CONVERT(VARCHAR(32), CURRENT_TIMESTAMP,109 )PRINT 'Server : ' + @@SERVERNAMEPRINT 'Host Name/ID : ' + HOST_NAME() + '/' + CONVERT(VARCHAR(32),HOST_ID())PRINT 'Database : ' + DB_NAME()PRINT 'User/NT User : ''' + USER_NAME() + '''/''' + SYSTEM_USER +''''PRINT 'DEBUG FLAG : ' + CONVERT( CHAR(1), @DEBUG )PRINT '=== BEGIN ==='PRINT SPACE(1)ENDIF ( EXISTS ( SELECT 1 FROM sysobjects WHEREid=object_id(N'Employees_temp') ) )DROP TABLE Employees_tempCREATE TABLE Employees_temp(emp_id INTEGER, lastname VARCHAR(70))INSERT INTO Employees_temp([emp_id],[lastname])SELECT EmployeeID, lastnameFROM EmployeesIF ( @cur = 1 )BEGINDECLARE curEmp CURSOR FORSELECT emp_id, lastnameFROM Employees_tempOPEN curEmpFETCH NEXT FROM curEmpINTO@emp_id, @lastnameWHILE ( @@FETCH_STATUS = 0 )BEGINFETCH NEXT FROM curEmpINTO@emp_id, @lastnameENDCLOSE curEmpDEALLOCATE curEmpENDSELECT emp_id, lastnameFROM Employees_tempGO
View Replies !
Urgent : Maximum Stored Procedure, Function, Trigger, Or View Nesting Level Exceeded
Hi all, I have writen a Function which call's the same function it self. I'm getting the error as below. Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32). Can any one give me a solution for this problem I have attached the function also. CREATE FUNCTION dbo.GetLegsFor(@IncludeParent bit, @EmployeeID float) RETURNS @retFindReports TABLE (EmployeeID float, Name nvarchar(255), BossID float) AS BEGIN IF (@IncludeParent=1) BEGIN INSERT INTO @retFindReports SELECT MemberId,Name,referredby FROM Amemberinfo WHERE Memberid=@EmployeeID END DECLARE @Report_ID float, @Report_Name nvarchar(255), @Report_BossID float DECLARE RetrieveReports CURSOR STATIC LOCAL FOR SELECT MemberId,Name,referredby FROM Amemberinfo WHERE referredby=@EmployeeID OPEN RetrieveReports FETCH NEXT FROM RetrieveReports INTO @Report_ID, @Report_Name, @Report_BossID WHILE (@@FETCH_STATUS = 0) BEGIN INSERT INTO @retFindReports SELECT * FROM dbo.GetLegsFor(0,@Report_ID) INSERT INTO @retFindReports VALUES(@Report_ID,@Report_Name, @Report_BossID) FETCH NEXT FROM RetrieveReports INTO @Report_ID, @Report_Name, @Report_BossID END CLOSE RetrieveReports DEALLOCATE RetrieveReports RETURN END
View Replies !
Help Cursor Based Stored Procedure Is Getting Slower And Slower!
I am begginner at best so I hope someone that is better can help.I have a stored procedure that updates a view that I wrote using 2cursors.(Kind of a Inner Loop) I wrote it this way Because I couldn'tdo it using reqular transact SQL.The problem is that this procedure is taking longer and longer to run.Up to 5 hours now! It is anaylizing about 30,000 records. I thinkpartly because we add new records every month.The procedure works like this.The first Cursor stores a unique account and duedate combination fromthe view.It then finds all the accts in the view that have that account duedatecombo and loads them into Cursor 2 this groups them together for datamanipulation. The accounts have to be grouped this way because aaccount can have different due dates and multiple records within eachaccount due date combo and they need to be looked at this way aslittle singular groups.Here is my procedure I hope someone can shead some light on this. Myboss is giving me heck about it. (I think he thinks Girls cant code!)I got this far I hope someone can help me optimize it further.CREATE PROCEDURE dbo.sp_PromiseStatusASBEGINSET NOCOUNT ON/* Global variables */DECLARE @tot_pay moneyDECLARE @rec_upd VARCHAR(1)DECLARE @todays_date varchar(12)DECLARE @mActivityDate2_temp datetimeDECLARE @tot_paydate datetime/* variables for cursor ACT_CUR1*/DECLARE @mAcct_Num1 BIGINTDECLARE @mDueDate1 datetime/* variables for ACT_CUR2 */DECLARE @mAcct_Num2 BIGINTDECLARE @mActivity_Date2 datetimeDECLARE @mPromise_Amt_1 moneyDECLARE @mPromise_Status varchar(3)DECLARE @mCurrent_Due_Amt moneyDECLARE @mDPD intDECLARE @mPromise_Date datetimeSELECT @todays_date =''+CAST(DATEPART(mm,getdate()) AS varchar(2))+'/'+CAST(DATEPART(dd,getdate()) AS varchar(2))+'/'+CAST(DATEPART(yyyy,getdate()) AS varchar(4))+''DECLARE ACT_CUR1 CURSOR FORSELECT DISTINCTA.ACCT_NUM,A.DUE_DATEFROM VWAPPLICABLEPROMISEACTIVITYRECORDS AOPEN ACT_CUR1FETCH NEXT FROM ACT_CUR1 INTO @mAcct_Num1 , @mDueDate1WHILE (@@FETCH_STATUS = 0)BEGINSELECT @rec_upd = 'N 'DECLARE ACT_CUR2 CURSOR FORSELECTB.ACCT_NUM,B.ACTIVITY_DATE,B.PROMISE_AMT_1,B.PROMISE_STATUS,B.CURRENT_DUE_AMT,B.DAYS_DELINQUENT_NUM,B.PROMISE_DATE_1FROM VWAPPLICABLEPROMISEACTIVITYRECORDS B (UPDLOCK)WHERE B.ACCT_NUM = @mAcct_Num1ANDB.DUE_DATE = @mDueDate1ORDER BY B.ACCT_NUM,B.DUE_DATE,B.ACTIVITY_DATE,CASEB.Time_ObtainedWHEN 0 THEN 0ELSE 1END Desc, B.Time_ObtainedOPEN ACT_CUR2FETCH NEXT FROM ACT_CUR2INTO @mAcct_Num2 ,@mActivity_Date2,@mPromise_Amt_1,@mPromise_Status ,@mCurrent_Due_Amt,@mDPD,@mPromise_DateWHILE (@@FETCH_STATUS = 0)BEGIN----CHECK------------------------------------------------------------------------DECLARE @PrintVariable2 VARCHAR (8000)--SELECT @PrintVariable2 = CAST(@MACCT_NUM2 AS VARCHAR)+''+CAST(@MACTIVITY_DATE2 AS VARCHAR)+' '+CAST(@MPROMISE_AMT_1 ASVARCHAR)+' '+CAST(@MPROMISE_STATUS AS VARCHAR)+''+CAST(@mCurrent_Due_Amt AS VARCHAR)+' '+CAST(@mDPD AS VARCHAR)+''+CAST(@mPromise_Date AS VARCHAR)--PRINT @PrintVariable2----ENDCHECK------------------------------------------------------------IF @mDPD >= 30BEGINSELECT @tot_pay = SUM(CONVERT(FLOAT, C.PAY_AMT))FROM vwAplicablePayments CWHERE C.ACCT_NUM = @mAcct_Num2ANDC.ACTIVITY_DATE >= @mActivity_Date2ANDC.ACTIVITY_DATE < @mActivity_Date2 + 15----CHECK------------------------------------------------------------------------DECLARE @PrintVariable3 VARCHAR (8000)--SELECT @PrintVariable3 ='Greater=30 DOLLARS COLLECTED'--PRINT @PrintVariable3----ENDCHECK------------------------------------------------------------ENDELSE IF @mDPD < 30BEGINSELECT @tot_pay = SUM(CONVERT(FLOAT, C.PAY_AMT))FROM vwAplicablePayments CWHERE C.ACCT_NUM = @mAcct_Num2ANDC.ACTIVITY_DATE >= @mActivity_Date2ANDC.ACTIVITY_DATE BETWEEN @mActivity_Date2 AND@mPromise_Date + 5----CHECK----------------------------------------------------------------------DECLARE @PrintVariable4 VARCHAR (8000)--SELECT @PrintVariable4 ='Less 30 DOLLARS COLLECTED'--PRINT @PrintVariable4----END CHECK------------------------------------------------------------END----------------------------------------MY REVISEDLOGIC-------------------------------------------------------IF @rec_upd = 'N'BEGINIF @mDPD >= 30BEGINSELECT @mActivityDate2_temp = @mActivity_Date2 + 15--DECLARE @PrintVariable5 VARCHAR (8000)--SELECT @PrintVariable5 =' GREATER= 30 USING ACTVITY_DATE+15'--PRINT @PrintVariable5ENDELSE IF @mDPD < 30BEGINSELECT @mActivityDate2_temp = @mPromise_Date + 5--DECLARE @PrintVariable6 VARCHAR (8000)--SELECT @PrintVariable6 =' LESS 30 USING PROMISE_DATE+5'--PRINT @PrintVariable6ENDIF @tot_pay >= 0.9 * @mCurrent_Due_Amt--used to be promise amtBEGINUPDATE VWAPPLICABLEPROMISEACTIVITYRECORDSSET PROMISE_STATUS = 'PK',TOTAL_DOLLARS_COLL = @tot_payWHERE CURRENT OF ACT_CUR2--This statement updates the time that the status was placedinto PK.IF @mPromise_Status IN ('PTP','OP')BEGINUPDATE VWAPPLICABLEPROMISEACTIVITYRECORDSSET Status_Date = @todays_dateWHERE CURRENT OF ACT_CUR2ENDSELECT @rec_upd = 'Y 'ENDIF ((@tot_pay < 0.9 * @mCurrent_Due_Amt) OR @tot_pay IS NULL)AND( @mActivityDate2_temp > @todays_date )--need to put 1dayof month here for snapshot9/01/2004BEGINUPDATE VWAPPLICABLEPROMISEACTIVITYRECORDSSETPROMISE_STATUS = 'OP'WHERE CURRENT OF ACT_CUR2--This statement updates the time that the status was placedinto OP which is the original Activity Date.--The record will hold this date until it goes into PK,PB,orIP.IF @mPromise_Status IN ('PTP','OP')BEGINUPDATE VWAPPLICABLEPROMISEACTIVITYRECORDSSET Status_Date = @mActivity_Date2WHERE CURRENT OF ACT_CUR2ENDENDELSE IF ((@tot_pay < 0.9 * @mCurrent_Due_Amt) OR @tot_pay ISNULL)AND( @mActivityDate2_temp <= @todays_date )--need to put 1dayof month here for snapshot 9/01/2004BEGINUPDATE VWAPPLICABLEPROMISEACTIVITYRECORDSSETPROMISE_STATUS = 'PB',TOTAL_DOLLARS_COLL = case when @tot_pay is nullthen 0 else @tot_pay endWHERE CURRENT OF ACT_CUR2--This statement updates the time that the status was placedinto PB.IF @mPromise_Status IN ('PTP','OP')BEGINUPDATE VWAPPLICABLEPROMISEACTIVITYRECORDSSET Status_Date = @todays_dateWHERE CURRENT OF ACT_CUR2ENDENDENDELSE IF @rec_upd = 'Y'BEGINUPDATE VWAPPLICABLEPROMISEACTIVITYRECORDSSETPROMISE_STATUS = 'IP',TOTAL_DOLLARS_COLL = 0WHERE CURRENT OF ACT_CUR2--This statement updates the time that the status was placedinto IP.IF @mPromise_Status NOT IN ('IP')BEGINUPDATE VWAPPLICABLEPROMISEACTIVITYRECORDSSET Status_Date = @todays_dateWHERE CURRENT OF ACT_CUR2ENDENDFETCH NEXT FROM ACT_CUR2 INTO @mAcct_Num2,@mActivity_Date2,@mPromise_Amt_1,@mPromise_Status ,@mCurrent_Due_Amt,@mDPD,@mPromise_DateENDCLOSE ACT_CUR2DEALLOCATE ACT_CUR2FETCH NEXT FROM ACT_CUR1 INTO @mAcct_Num1 , @mDueDate1ENDCLOSE ACT_CUR1DEALLOCATE ACT_CUR1SET NOCOUNT OFFENDGO
View Replies !
Urgent. Output Columns Are Not Appearing When I Use OLEDB Data Source With An Oracle Stored Procedure In Dataflow Task
I am using execute sql task to run a stored procedure in oracle database which returns a resultset. This works. Now I need to send the ouput to a destination table in a sql database. Should I use for each loop to pick the resultset and insert it into the destination one by one (which I dont think is a great idea) or is there a better way to accomplish this task (in data flow task) ? When I use dataflow task instead of execute sql task, the main issue is I am not able to see the output columns when I execute an oracle stored procedure, but when I see the preview I can see the resultset . But I can see the output columns for a sql server stored procedure.
View Replies !
Urgent: Cursor Already Open Error
I get the following errors while running a SQL procedure. [ODBC][Microsoft][ODBC SQL Server Driver][SQL Server]The cursor is already open [ODBC][Microsoft][ODBC SQL Server Driver][SQL Server]A cursor with the name 'qst_Ruler_AllExpenses' already exists I am creating, opening and deallocating the cursor. Advice please.
View Replies !
UPDATE TRIGGER WITH CURSOR... URGENT HELP..
HI EVERYBODY.. SQL 7.0: WE HAVE A TABLE X WHICH HAS AN UPDATE TRIGGER WRITTEN ON IT WHICH IS FIRED ON UPDATATION ON THIS TABLE. WE HAVE AN ENHANCEMENT TO THIS TRIGGER WHICH WOULD INSERT THE LAST UPDATED ROW IN TABLE X (THROUGH LOGICAL TABLE 'INSERTED') FOR ONLY FEW COLUMNS INTO ANOTHER TABLE Y ON ANOTHER DATABASE. WE HAVE TRIED USING CURSORS FOR PASSING VARIABLE FROM THE INSERTED ROW TO THE FINAL TABLE, BUT WE SEEM TO NOT GET ANY DATA INTO THE TABLE Y. HOW CAN WE TEST IF THE VALUES IN THE CURSOR VARIABLES ARE BEING PASSED? PLEASE LET ME KNOW HOW TO APPROACH THE PROBLEM. THANKS IN ADVANCE.. BYE MO
View Replies !
How To Return Multiple Results In 1 Fetch Cursor- Urgent Help!
I want to send 1 email with all clientname records which the cursor gets for me. My code however is sending 1 email for 1 record i.e clientname got from db. What's wrong? please help. I ano table to understand here about the while if right. thanks. +++++++++++++++++++++++++++++++++++++++++ CREATE PROCEDURE test1 AS declare @clientName varchar(1000) declare myCursor CURSOR STATIC for select client_name from clients ------------------------- -- now prepare and send out the e-mails declare @ToEmail varchar(255) declare @FromEmail varchar(255) declare @Subject varchar(255) declare @Body varchar(2000) declare @UserID numeric(38) declare @UserName varchar(255) declare @SMTPServer varchar(100) set @SMTPServer = 'test.testserver.com' -- loop for each record open myCursor fetch next from myCursor into @clientName --loop now: while (@@fetch_status=0) begin -- while(@@fetch_status=0) -- check if valid "To" e-mail address was found if ((@clientName is null) or (ltrim(@clientName) = '')) begin --should not come here anytime ideally set @FromEmail = 'me@test.com' set @ToEmail = 'me@test.com' set @Subject = 'was emailed to wrong person' set @Body = 'the client name got is : '+ @clientName + 'client is null or empty' end --if else begin set @FromEmail = 'me@test.com' set @ToEmail = 'me@test.com' set @Subject = '-testing' set @Body = 'this will send ClientName:'+ @clientName end --end else -- send the e-mail --exec dbo.usp_SendCDOSysMailWithAuth @FromEmail, @ToEmail, @Subject, @Body, 0, @SMTPServer --fetch next from myCursor into @clientName fetch next from myCursor into @clientName end --while(@@fetch_status=0) exec dbo.usp_SendCDOSysMailWithAuth @FromEmail, @ToEmail, @Subject, @Body, 0, @SMTPServer close myCursor deallocate myCursor GO
View Replies !
Calling A Stored Procedure From ADO.NET 2.0-VB 2005 Express: Working With SELECT Statements In The Stored Procedure-4 Errors?
Hi all, I have 2 sets of sql code in my SQL Server Management Stidio Express (SSMSE): (1) /////--spTopSixAnalytes.sql--/// USE ssmsExpressDB GO CREATE Procedure [dbo].[spTopSixAnalytes] AS SET ROWCOUNT 6 SELECT Labtests.Result AS TopSixAnalytes, LabTests.Unit, LabTests.AnalyteName FROM LabTests ORDER BY LabTests.Result DESC GO (2) /////--spTopSixAnalytesEXEC.sql--////////////// USE ssmsExpressDB GO EXEC spTopSixAnalytes GO I executed them and got the following results in SSMSE: TopSixAnalytes Unit AnalyteName 1 222.10 ug/Kg Acetone 2 220.30 ug/Kg Acetone 3 211.90 ug/Kg Acetone 4 140.30 ug/L Acetone 5 120.70 ug/L Acetone 6 90.70 ug/L Acetone ///////////////////////////////////////////////////////////////////////////////////////////// Now, I try to use this Stored Procedure in my ADO.NET-VB 2005 Express programming: //////////////////--spTopSixAnalytes.vb--/////////// Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sqlConnection As SqlConnection = New SqlConnection("Data Source = .SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = ssmsExpressDB;") Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdaptor("[spTopSixAnalytes]", sqlConnection) sqlDataAdapter.SelectCommand.Command.Type = CommandType.StoredProcedure 'Pass the name of the DataSet through the overloaded contructor 'of the DataSet class. Dim dataSet As DataSet ("ssmsExpressDB") sqlConnection.Open() sqlDataAdapter.Fill(DataSet) sqlConnection.Close() End Sub End Class /////////////////////////////////////////////////////////////////////////////////////////// I executed the above code and I got the following 4 errors: Error #1: Type 'SqlConnection' is not defined (in Form1.vb) Error #2: Type 'SqlDataAdapter' is not defined (in Form1.vb) Error #3: Array bounds cannot appear in type specifiers (in Form1.vb) Error #4: 'DataSet' is not a type and cannot be used as an expression (in Form1) Please help and advise. Thanks in advance, Scott Chang More Information for you to know: I have the "ssmsExpressDB" database in the Database Expolorer of VB 2005 Express. But I do not know how to get the SqlConnection and the SqlDataAdapter into the Form1. I do not know how to get the Fill Method implemented properly. I try to learn "Working with SELECT Statement in a Stored Procedure" for printing the 6 rows that are selected - they are not parameterized.
View Replies !
Cursor And Procedure
Hello: I want find that the ntext column data string have more than 2000 characters. I need to truncate those string to segment with 200 character, then put those segments along with their table_name and column_name to another table. Maybe need to use cursor? If so, how to use it? Your help is highly appreciated. s
View Replies !
Cursor In Procedure
Hi I am trying to write one cursor which is been made from join of two tables. and then i want to update one table by using where current of cursor. Can i do that..? or should i create the view by joining the two tables and then try to update it. or should i create the temp table and put the records in that and then try to update that. Please guide me in this. Thanks, Harish ==== CREATE PROCEDURE SP_P4 AS declare c123 cursor for select COMPANY.COMPANY, COMPANY.COMPANYNAME, COMPANY.CUSTOMERNUMBER, COMPANY.FEDTAXID, COMPANY.DUNSNUMBER, COMPANY.S1099, COMPANY.DUNSSUFFIX, COMPANYADDRESS.ADDRESSSEQ, COMPANYADDRESS.COUNTRY, COMPANYADDRESS.ADDRESSTYPE, COMPANYADDRESS.ADDRESS1, COMPANYADDRESS.ADDRESS2, COMPANYADDRESS.ADDRESS3, COMPANYADDRESS.ADDRESS4, COMPANYADDRESS.CITY, COMPANYADDRESS.STATE, COMPANYADDRESS.ZIP from COMPANY,COMPANYADDRESS where company.company=COMPANYADDRESS.company order by company.company declare @company char declare @COMPANYNAME char declare @CUSTOMERNUMBER char declare @FEDTAXID char declare @DUNSNUMBER char declare @S1099 char declare @DUNSSUFFIX char declare @ADDRESSSEQ int declare @COUNTRY char declare @ADDRESSTYPE char declare @ADDRESS1 char declare @ADDRESS2 char declare @ADDRESS3 char declare @ADDRESS4 char declare @CITY char declare @STATE char declare @ZIP char open c123 fetch next from c123 into @company,@COMPANYNAME,@CUSTOMERNUMBER,@FEDTAXID,@D UNSNUMBER,@S1099, @DUNSSUFFIX,@ADDRESSSEQ,@COUNTRY,@ADDRESSTYPE,@ADD RESS1,@ADDRESS2,@ADDRESS3,@ADDRESS4,@CITY, @STATE,@ZIP while @@fetch_status=0 begin update companyaddress set ADDRESSSEQ=@ADDRESSSEQ where current of c123 update companyaddress set COUNTRY=@COUNTRY where current of c123 update companyaddress set ADDRESSTYPE=@ADDRESSTYPE where current of c123 update companyaddress set ADDRESS1=@ADDRESS1 where current of c123 update companyaddress set ADDRESS2=@ADDRESS2 where current of c123 update companyaddress set ADDRESS3=@ADDRESS3 where current of c123 update companyaddress set ADDRESS4=@ADDRESS4 where current of c123 update companyaddress set CITY=@CITY where current of c123 update companyaddress set STATE=@STATE where current of c123 update companyaddress set ZIP=@ZIP where current of c123 fetch next from c123 into @company,@COMPANYNAME,@CUSTOMERNUMBER,@FEDTAXID,@D UNSNUMBER,@S1099, @DUNSSUFFIX,@ADDRESSSEQ,@COUNTRY,@ADDRESSTYPE,@ADD RESS1,@ADDRESS2,@ADDRESS3,@ADDRESS4,@CITY, @STATE,@ZIP end close c123 deallocate c123 declare @v datetime declare @filename varchar(32) select @v=getdate() select @filename = 'XAPIALTMKT'+CONVERT(varchar, @v, 112)+ SUBSTRING(CONVERT(varchar, @v, 108), 1, 2) + SUBSTRING(CONVERT(varchar, @v, 108), 4, 2)+ SUBSTRING(CONVERT(varchar, @v, 108), 7, 2) + '.TXT' declare @cmdstring varchar(255) Select @cmdstring = 'bcp conversion..expt1 out d:est' + @filename + ' -c -t"|" -r -S -Usa -Psa' exec master..xp_cmdshell @cmdstring drop table expt1
View Replies !
|