Create A Cursor Inside A Sproc
I try to create a Sproc which will use a cursor to retrieve a few rows from a table. But the cursor part has given me problem. Here it is:
StudentInfo
StudentID StudentName DeptID
101 John 10
102 Alex 10
103 Beth 20
ClassInfo
ClassID DeptID
901 10
902 10
225 20
I want to create a Sproc which will retreive the student's classes in DeptID 10
Following is the Sproc and cursor:
use master
go
Create PROCEDURE [dbo].[getEnclishClasses]
@StudentID int
AS
Declare @printInsertStatement nvarchar(100)
ECLARE NewRowID int
Declare classCursor CURSOR FOR
SELECT ClassID, DeptID FROM [myTest].dbo.ClassInfo
WHERE DeptID=(SELECT DeptID FROM [myTest].dbo.StudentInfo
WHERE StudentID=@StudentID)
DECLARE @ClassID INT
DECLARE @DeptID INT
OPEN classCursor
FETCH NEXT FROM classCURSOR INTO
@ClassID, @DeptID
WHILE (@@FETCH_STATUs=0)
BEGIN
PRINT 'SET @newID = Scope_Identity()'
SET @printInsertStatement=
(Select 'INSERT INTO [myTest].dbo.ClassInfo (ClassID, DeptID) Values('
+CONVERT(NVARCHAR (10), @ClassID) + ','
+CONVERT(NVARCHAR (2), @DeptID)+')'
FROM [myTest].dbo.StudentInfo
WHERE DeptID=(SELECT DeptID FROM [myTest].dbo.StudentInfo
WHERE StudentID=@StudentID))
PRINT @printInsertStatement
END
CLOSE classCursor
DEALLOCATE classCursor
EXEC getEnclishClasses 101
Here is what I try to get (text with actual data from the table):
SET @newRowID = Scope_Identity()
INSERT INTO [myTest].dbo.ClassInfo VALUES(901, 10)
SET @newRowID = Scope_Identity()
INSERT INTO [myTest].dbo.ClassInfo VALUES(902, 10)
Here is what I had got (returning multiple lines, more than number of records I have):
Msg 512, Level 16, State 1, Procedure getEnclishClasses, Line 19
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Thanks in advance for your help! Or is it a better way (not using a cursor). Each table has over 5,000 records.
View Complete Forum Thread with Replies
Related Forum Messages:
Unable To Execute Job Inside Sproc From Reporting Services
We have a request to build a report based on user input from an excel spreadsheet. We have a SSIS package that imports the data from Excel. This is run by a sql server agent job. Our stored procedure executes this job and runs this whole process just fine but when we execute the stored procedure from reporting services we get errors. Has anyone done this type of thing before and do you have any working solutions for how to get this reporting methodology to function? Thanks!
View Replies !
Logic Problem In Cursor/SPROC
SQL Server 2000I have a stored procedure that uses an extended SPROC to send an emailnotification to my customers when a document is distributed.However, the SPROC has an unexpected side effect.If I run it in its current incarnation, it only sends one email andthen exits. However, if I remove or comment out the block/* Set Job to processed */UPDATEtblJobsSETfldEmailProcessed = 1WHERE(fldJobID = @JobID)then it runs through the whole list as anticipated. Conceptually, itseems that the records in the cursor are changed if the underlyingtable is updated.Here is pseudo-code for what the SPROC does - whole SPROC below (withpart of the "WHERE" clause removed for readability). I haven'tincluded any table schemae but I don't think they're relevant.1. Open a cursor and fetch a list of all companies that need emailnotification for pending jobs.2. While records in the cursor...a) Format and send email from the cursorb) Write a record to the audit tablec) Update the jobs table for the current record3) Fetch next from cursorThere is an update trigger on the tblJobs table thus:CREATE TRIGGER "tblJobs_UTrig" ON dbo.tblJobs FOR UPDATE ASSET NOCOUNT ON/* * PREVENT UPDATES IF NO MATCHING KEY IN 'tblDistributionMaster' */IF UPDATE(fldDistributionID)BEGINIF (SELECT COUNT(*) FROM inserted) !=(SELECT COUNT(*) FROM tblDistributionMaster, inserted WHERE(tblDistributionMaster.fldDistributionID = inserted.fldDistributionID))BEGINRAISERROR 44446 'The record can''t be added or changed.Referential integrity rules require a related record in table''tblDistributionMaster''.'ROLLBACK TRANSACTIONENDEND/* * PREVENT UPDATES IF DEPENDENT RECORDS IN 'tblPrinterJobs' */IF UPDATE(fldJobID)BEGINIF (SELECT COUNT(*) FROM deleted, tblPrinterJobs WHERE(deleted.fldJobID = tblPrinterJobs.fldJobID)) > 0BEGINRAISERROR 44446 'The record can''t be deleted orchanged. Since related records exist in table ''tblPrinterJobs'',referential integrity rules would be violated.'ROLLBACK TRANSACTIONENDENDI can't see that this is relevant - I think it's something to do withwhere I'm updating the fldEmailProcessed field, but I need to do thishere, as outside the loop the fldJobID might be lost.Sorry it's all such a mess. Hope someone can help!ThanksEdward/*Checks all Jobs that were set to Despatched more than 24 hours ago,selects those that the companies elected to get email notification, andsends them emails.*/CREATE PROCEDURE stpSendEmailNotificationASDECLARE @rc intDECLARE @JobID intDECLARE @CompanyID intDECLARE @DocumentNumber varchar(50)DECLARE @Email varchar(50)DECLARE @DocumentURL varchar(750)DECLARE @Dat varchar(20)DECLARE @Subject varchar(100)SET @Dat = LEFT((CONVERT(varchar, GETDATE(), 100)), 11)DECLARE MailList CURSOR FORSELECTtblJobs.fldJobID,tblJobs.fldDocumentNumber,tblCompany.fldEmail,tblCompany.fldCompanyID,tblJobHistory.fldDocumentURLFROMtblJobHistory INNER JOINtblJobs ON tblJobHistory.fldJobID = tblJobs.fldJobIDINNER JOINtblDistributionMaster ON tblJobHistory.fldDistributionID =tblDistributionMaster.fldDistributionID INNER JOINtblCompany ON tblJobHistory.fldCompanyID =tblCompany.fldCompanyIDWHERE(tblJobs.fldEmailProcessed = 0)OPEN MailListFETCH NEXT FROM MailList INTO@JobID,@DocumentNumber,@Email,@CompanyID,@DocumentURLWHILE @@FETCH_STATUS = 0BEGIN/* Format and send the email to the customer here */SET @Subject = N'Document Distribution No: ' + @DocumentNumber +N' - Date: ' + @Datexec @rc = master.dbo.xp_smtp_sendmail@FROM = N'techlib@myco.co.uk',@FROM_NAME = N'Edward Collier',@replyto = N'techlib@myco.co.uk',@TO = @Email,@CC = N'',@BCC = N'',@priority = N'NORMAL',@subject = @Subject,@type = N'text/plain',@message = @DocumentURL,@messagefile = N'',@attachment = N'',@attachments = N'',@codepage = 0,@server = N'12.34.5.67',@timeout = 10000select RC = @rc/* Write result to audit table */INSERT INTO tblEmailAudit(fldRCNo,fldEmail,fldDocumentNumber,fldDate,fldCompanyID)VALUES(@rc,@Email,@DocumentNumber,GETDATE(),@CompanyID)/* Set Job to processed */UPDATEtblJobsSETfldEmailProcessed = 1WHERE(fldJobID = @JobID)FETCH NEXT FROM MailList INTO@JobID,@DocumentNumber,@Email,@CompanyID,@DocumentURLENDCLOSE MailListDEALLOCATE MailListGO
View Replies !
Cursor In Sproc To Kill Spids Loops Forever
I need a stored proc to kill spids, but the following sproc loops infinitely with the same [correct] spid being printed out. What am I doing wrong? The select statement, when I execute it via the query grid, returns the correct and finite number of spids. Any help greatly appreciated. Judith CREATE PROCEDURE rasp_KillDBProcess @dbname varchar(128) AS declare @KillSpid smallint declare @SQL varchar(1000) -- declare DBCursor cursor Forward_only for SELECT distinct l.spid FROM master.dbo.syslocks l INNER JOIN master.dbo.sysdatabases d ON l.dbid = d.dbid WHERE (d.name = N'coj_pcisdata') open DBCursor -- Fetch next from DBCursor into @Killspid -- While (@@Fetch_status <> -1) Begin If (@@Fetch_status <> -2) begin print 'spid = ' + cast(@killspid as varchar(12)) --exec ('kill ' + @killspid) end -- end Fetch next from DBCursor into @Killspid -- close dbcursor deallocate dbcursor print 'end' return
View Replies !
Loop Inside Of A Cursor
I have a loop(while) statement I need to run inside a cursor statement. The loop creates records based on a frequency. The cursor and the loop work but the problem is that the cursor only reads the first record, runs the loop, but then ends. I am pasting the code below. Any help appreciated declare dbcursor cursor for select uniq_id,account_id,created_by,encounter_id, start_date,date_stopped,sig_codes, ndc_id,modified_by from patient_medication where convert(datetime,start_date) = '10/20/2000' and date_stopped is not null open dbcursor fetch next from dbcursor into @uniqid,@account_id,@createid,@entcid, @sdate, @edate ,@sig_code, @ndcid, @modid while (@@FETCH_STATUS <> -1) begin select @freq = SIG.sig_frequency FROM SIG where SIG.SIG_KEY = @sig_code set @hfreq = @freq if @freq = 9 set @freq = 1 set @nodays = datediff(day, @sdate - 1, @edate) while @cnter < @nodays begin while @fcnter < @freq + 1 begin insert into PATIENT_MEDICATION_DISPERSAL_ (uniq_id,account_id, occurance_id, encounter_id, ndc_id, ddate, frequency, sig_code,disp_create_id, disp_mod_id) values (@uniqid,@account_id,@fcnter, @entcid, @ndcid, @sdate, @freq, @sig_code,@createid, @modid ) set @fcnter = @fcnter + 1 set @erdate = @sdate END if @hfreq = 9 begin set @fcnter = 1 set @sdate = @sdate + 2 Set @cnter = @cnter + 2 end else begin set @fcnter = 1 set @sdate = @sdate + 1 Set @cnter = @cnter + 1 end end end close dbcursor deallocate dbcursor
View Replies !
Copy Subtree, Recursive Sproc With Cursor Doesn't Work
Hi all, I have a parent-child table, and i want to copy subtrees of it, so for instance this would be the starting point: (id, parentId, label) 0, null, World 1, 0, US 2, 1, NY 3, 0, UK 4, 3, London now i want to copy object 3 (UK) and it's children, so i would get 0, null, World 1, 0, US 2, 1, NY 3, 0, UK 4, 3, London 5, 0, UK_copy 6, 5, London_copy I have this sproc: Code Snippet alter proc CopyObject (@ObjectId int, @NewParentId int) as declare @NewId int, @NewName varchar select @NewId = max(Id) + 1 from Object select @NewName = [Name] + 'copy' from [Object] where Id = @ObjectId -- copy object INSERT INTO [Object] ([Id] ,[Name] ,[ParentId] select @NewId, @NewName, @NewParentId from [Object] where Id = @ObjectId -- copy children and set their parent to the newly created object declare c cursor fast_forward for select Id from [Object] where ParentId = @ObjectId declare @ChildId int open c fetch next from c into @ChildId while @@fetch_status = 0 begin exec CopyObject @ObjectID = @ChildId, @NewParentId = @NewId fetch next from c into @ChildId end close c deallocate c But htis throws an error that the cursor already exists: Msg 16915, Level 16, State 1, Procedure CopyObject, Line 66 A cursor with the name 'c' already exists. Msg 16905, Level 16, State 1, Procedure CopyObject, Line 72 The cursor is already open. I've tried to think of an approach without cursors, but i can't figure it out. Because on the first pass, the new parentId will be the same as the parentId of the object to be copied. But the copies of the children of this first original object should have the parentid set to id of the copied object, and so all the way down the tree. Any ideas? Thanks in advance, Gert-Jan
View Replies !
Cursor Inside A Cursor
I'm new to cursors, and I'm not sure what's wrong with this code, it run for ever and when I stop it I get cursor open errors declare Q cursor for select systudentid from satrans declare @id int open Q fetch next from Q into @id while @@fetch_status = 0 begin declare c cursor for Select b.ssn, SaTrans.SyStudentID, satrans.date, satrans.type, SaTrans.SyCampusID, Amount = Case SaTrans.Type When 'P' Then SaTrans.Amount * -1 When 'C' Then SaTrans.Amount * -1 Else SaTrans.Amount END From SaTrans , systudent b where satrans.systudentid = b.systudentid and satrans.systudentid = @id declare @arbalance money, @type varchar, @ssn varchar, @amount money, @systudentid int, @transdate datetime, @sycampusid int, @before money set @arbalance = 0 open c fetch next from c into @ssn, @systudentid, @transdate, @type, @sycampusid, @amount while @@fetch_status = 0 begin set @arbalance = @arbalance + @amount set @before = @arbalance -@amount insert c2000_utility1..tempbalhistory1 select @systudentid systudentid, @sycampusid sycampusid, @transdate transdate, @amount amount, @type type, @arbalance Arbalance, @before BeforeBalance where( convert (int,@amount) <= -50 or @amount * -1 > @before * .02) and @type = 'P' fetch next from c into @ssn, @systudentid, @transdate, @type, @sycampusid, @amount end close c deallocate c fetch next from Q into @id end close Q deallocate Q select * from c2000_utility1..tempbalhistory1 truncate table c2000_utility1..tempbalhistory1
View Replies !
Calling A SP Inside A Cursor Loop..
I have SP, which has a cursor iterations. Need to call another SP forevery loop iteration of the cursor. The pseudo code is as follows..Create proc1 asBeginVariable declrations...declare EffectiveDate_Cursor cursor forselect field1,fld2 from tab1,tab2 where tab1.effectivedate<Getdate()---/////Assuming the above query would result in 3 recordsOpen EffectiveDate_CursorFetch next From EffectiveDate_Cursor Into @FLD1,@FLD2begin/*Calling my second stored proc with fld1 as a In parameterand Op1 and OP2 Out parameters*/Exec sp_minCheck @fld1, @OP1 output,@OP2 outputDo something based on Op1 and Op2.endWhile @@Fetch_Status = 0Fetch next From EffectiveDate_Cursor Into @FLD1,@FLD2/* Assume If loop count is 3.and If the Fetch stmt is below the begin Stmt, the loop iterations are4 else the loop iterations are 2*/begin/*Calling my second stored proc with fld1 as a In parameter and Op1and OP2 Out parameters*/Exec sp_minCheck @fld1, @OP1 output,@OP2 outputDo something based on Op1 and Op2.endThe problem I had been facing is that, the when a stored proc is calledwithin the loop, the proc is getting into infinite loops.Any Help would be appreciated.Satish
View Replies !
EXEC Inside A Cursor Iteration Problem
I 've have a stored procedure that compares fields across databases.In order to do so it requires 2 values it acquires from 2 tables. Thesearch is based on the ID of the data owner and a subject:proc_evaluate_results @StudentId = '222222', Course = 'PSY101'In order to obtain those values I run a cursor accross my records andSELECT THEM INTO 2 @variables, which then replace 222222 and PSY101with dynamic values eg.--define a cursor etc.etc.WHILE @@cursor_fetch = 0BEGIN--do the cursor call INTO @varsEXEC proc_evaluate_results @StudentId = @studentID, @Course =@CourseCodeENDNow,the vars are being passed to the stored procedure and executed OK,but the cursor gets stuck on the last record and continues to evaluateit until stopped manually.If I comment out the EXEC and replace it with eg. PRINT @Course + ' |' + @CourseCode it runs fine, exiting after the last record.ThanksR>
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 !
Sproc Create View And Parameter Problem
In the below sproc I want to create a view based on the incoming parameter, which is a date passed on from VB in the format 01-01-2006. Yet getting that to work, seems quite a challenge. I've been dabbling a bit with the sproc and QA, passing the date parameter to it in varous forms, using both single, double and triple quotationmarks and changing the parameter type to datetime. I either wind up with a syntax error " Incorrect syntax near '01' " or " Unclosed quotation mark before the character string ". Anyone have a guess at how to fix this issue? Cheers, Trinsan REATE PROCEDURE KONTROL_DRdobbeltrapportering @rapdato as varchar AS if exists (select * from dbo.sysobjects where id = object_id(N'[KONTROL_vw_DRdobbeltrappbasis]') and OBJECTPROPERTY(id, N'IsView') = 1) drop view [KONTROL_vw_DRdobbeltrappbasis] EXEC(' CREATE VIEW KONTROL_vw_DRdobbeltrappbasis AS SELECT Gramex_DW.dbo.Programhoved.[Rettet af DR], Gramex_DW.dbo.Programlinie.Stationskode, Gramex_DW.dbo.Programlinie.Udsendelsesdato, Gramex_DW.dbo.Programlinie.[Udsendelses starttid], Gramex_DW.dbo.Programlinie.Rapporteringsdato, Gramex_DW.dbo.Programlinie.Mediekode, Gramex_DW.dbo.Programlinie.MUSANummer, Replace(Left(convert(varchar, [Gramex-ID]),11),''.'','''') AS GramexID, Gramex_DW.dbo.Programlinie.Side, Gramex_DW.dbo.Programlinie.Tracknummer, Gramex_DW.dbo.Programlinie.ISRC, Gramex_DW.dbo.Programlinie.Producentlandekode, Gramex_DW.dbo.Programlinie.Spilletid, Gramex_DW.dbo.Programlinie.Minuttakst, Gramex_DW.dbo.Programlinie.[Afregnet Station], Gramex_DW.dbo.Programlinie.[Afregnet den], Gramex_DW.dbo.Programlinie.[Afregnings ID], Gramex_DW.dbo.Programlinie.[Ur-opførelse], Gramex_DW.dbo.Programlinie.Talestof, Gramex_DW.dbo.Programlinie.[Betalt af DR], Gramex_DW.dbo.Programlinie.Kending, Gramex_DW.dbo.Programlinie.[Oprettelses ID], Gramex_DW.dbo.Programlinie.[Oprettet den], Gramex_DW.dbo.Programlinie.[Oprettet af], Gramex_DW.dbo.Programlinie.[Ændret den], Gramex_DW.dbo.Programlinie.[Ændret af], Gramex_DW.dbo.Programlinie.[Eventuel delskæring], Gramex_DW.dbo.Programlinie.Plademærkenavn, Gramex_DW.dbo.Programlinie.Katalogbetegnelse, Gramex_DW.dbo.Programlinie.Tracktitel, Gramex_DW.dbo.Programlinie.Selskabsnummer, Gramex_DW.dbo.Programlinie.Indspilningsår, Gramex_DW.dbo.Programlinie.Fonogramtitel, Gramex_DW.dbo.Programlinie.Plademærkenummer, Gramex_DW.dbo.Programlinie.[Antal opførelser], Gramex_DW.dbo.Programlinie.[Rec nummer], Gramex_DW.dbo.Programlinie.Indslagsnummer, Gramex_DW.dbo.Programlinie.[Afspillet gange], Gramex_DW.dbo.Programlinie.[Afspillet minutter], Gramex_DW.dbo.Programlinie.Spilletidsløbenummer, Gramex_DW.dbo.Programlinie.Pointtildelt, Gramex_DW.dbo.Programlinie.[Rettet af Gramex], Gramex_DW.dbo.Programlinie.[Pgmkorlinie løbenummer], Gramex_DW.dbo.Programlinie.[Tape Kilde], Gramex_DW.dbo.Programlinie.[Hoved artist], Gramex_DW.dbo.Programhoved.Produktionsnummer FROM Gramex_DW.dbo.Programlinie INNER JOIN Gramex_DW.dbo.Programhoved ON (Gramex_DW.dbo.Programlinie.Stationskode = Gramex_DW.dbo.Programhoved.Stationskode) AND (Gramex_DW.dbo.Programlinie.Udsendelsesdato = Gramex_DW.dbo.Programhoved.Udsendelsesdato) AND (Gramex_DW.dbo.Programlinie.[Udsendelses starttid] = Gramex_DW.dbo.Programhoved.[Udesendelses starttid]) WHERE Gramex_DW.dbo.Programlinie.Rapporteringsdato >= ' + @rapdato + ' AND (Gramex_DW.dbo.Programlinie.Mediekode <> 1) AND (Gramex_DW.dbo.Programlinie.Spilletid >= ''00:01:00'') AND (Gramex_DW.dbo.Programlinie.Stationskode <> ''TV2'') AND (Gramex_DW.dbo.Programlinie.Stationskode <> ''TV2 ZULU'') AND (Gramex_DW.dbo.Programlinie.Stationskode <> ''TV2 CHARLIE''') GO
View Replies !
Create A Schema/script From Inside T-SQL.?
I have been asked to implement the following as part of a replication scenario... When the client runs the T-SQL script that creates the publication and its articles, we want to execute <something> that creates the current SQL creation script for the table that underlies the article. (Which in turn is used to automatically synchronize new subscriptions.) They want this automated, so that there is no need for anyone to worry about manually keeping a copy of the creation script for the table up-to-date. The functionality is given by "Generate SQL scripts" in the Enterprise manager, but I want to be able to call in programatically... any suggestions? As this is pressing, a note to me at bph@kirk.nt.ca if/when you post any replies would be most appreciated. -- Byron Hynes
View Replies !
How To Dynamically Create SQL Inside A Stored Procedure?
I am having problem with 'TOP @pageSize'. It doesn't work, but if I replace it by 'TOP 5' or 'TOP 6' etc., then the stored procedure runs without errors. Can someone please tell me how I could use @pageSize here so that it dynamically determines the 'n' of 'TOP n' ? ALTER PROCEDURE dbo.spGetNextPageRecords ( @pageSize int, @previousMaxId int ) AS /* SET NOCOUNT ON */ SELECT Top @pageSize ProductId, ProductName FROM Products WHERE (ProductID > @previousMaxId) order by ProductId RETURN
View Replies !
Manualy Create IDENTITY Column Inside ControlFlow
Dear Friends... I'm having a problem... I want to manually create the identity column for a table... I have some dataflws, and in each dataflow I insert values in this table... I need to start the controlflow in a SQL task to get the last ID and save it in a global variable with name D_INST_IDENTITY. And in each dataflow I have a script component transform, to get the ID... using a local variable COUNTER! and for each row I increment this value... Until this step there is no problem... the problem starts here...: I need to refresh the global variable in the final of each dataflow in order that in the next sequence dataflow I have D_INST_IDENTITY refreshed...... D_INST_IDENTITY = D_INST_IDENTITY + COUNTER How can I do it? I have a RowCount transform next the script component, but generates errors... What do you think I can do it? Thanks!!
View Replies !
CREATE FULLTEXT CATALOG Inside A User Transaction.
hi: I try to create full text for new created tables. Since all new created tables will have same columns with different table name. After I run the stored procedure to create table, after i got the new table name, I would like to create full-text on that table in the DDL triger. But I got error like this: CREATE FULLTEXT CATALOG statement cannot be used inside a user transaction. Any one has idea how to deal with it? Thanks
View Replies !
Is It Possible To Create A Class Library That I Can Import Inside Script Components In My Package?
Good day everyone, I have a package that loads data from a flat file, performs some transformations and then inserts the final data into a DB destination. The keys for the different DB records are generated in Script components in the Data Flow Tasks. My question is concerning the Key Generation and I'll try to explain it on a simple example. Package Structure: The Control Flow contains two Data Flow tasks. Each of the Data Flow Tasks contains a Script Component responsible for generating the keys of the records to be loaded during this data flow. The code of the Script component is the following: Code Block Imports System Imports System.Data Imports System.Math Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper Imports Microsoft.SqlServer.Dts.Runtime.Wrapper Public Class KeyGenerator ' Field Definitions ' Private seed1 As Integer Private seed2 As Integer ' Constructor ' Public Sub New(ByVal dbSeed1 As Integer, ByVal dbSeed2 As Integer) ..... End Sub ' Generates the keys according to the seeds retrieved from the DB ' Public Function getNextKey() As Int64 ... ... Return generatedKey End Function End Class Public Class ScriptMain Inherits UserComponent Private generator As New KeyGenerator(7, 5) Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer) .... Row.NewKey = generator.getNextKey() End Sub End Class Questions: As you can see the KeyGenerator class code gets duplicated in each Script Component, which is definitely a bad practise. What I wish to do is to create the KeyGenerator class and deploy it as a library "somewhere". Then, in each Script Component, I should only import the KeyGenerator class. 1. Is that possible? 2. If yes, how can I do this? 3. If not, what is a best practise you would recommend which allows me to avoid this code duplication of the KeyGenerator class? Thanks in adavance, Samar
View Replies !
Create View From Cursor
I have multiple locations that I want to create views for eachindividual location.I am using a cursor to create the views for each location. So, thecursor grabs site #1 then <should> create view_site_#1, then grab site#2 and <should> create view_site_#2.For some reason it doesn't like the view name with the @site in it.Any ideas of how to get this done?Here's the cursor...declare @site varchar(5)declare c_site cursor forselect station from VHAISLCAUDIA.VISN_SITEorder by stationopen c_sitefetch from c_siteinto @sitewhile (@@fetch_status = 0)beginCREATE VIEW Site_All_Data_+ @siteASSELECT *FROM dbo.[600_All_Suggested_Data]WHERE (Site = @site)Print 'View for ' + @site + ' Created'fetch next from c_site into @siteendclose c_sitedeallocate c_sitereturnend
View Replies !
Declare Or Create Cursor
Hello guys,just wanted to ask a question some might percieve it as a stupid one but I don't know so I will ask anyway? Is Declare Cursor same as Create Cursor and if not what is the major difference?
View Replies !
How Do I Create A "Cursor" In SQL Server 7.0??
How do I create a "Cursor" in SQL Server 7.0 that compares an imported table against a exsisting table? Ex. Table1 is my existing table(Destination), Table2 is my imported table(source). I would like to update records in the Destination from the Source but I have to be aware of these three scenarios. 1. If the record exist in the Destination and the Source I will do nothing. 2. If the record exist in the Source and not in the Destination then I will add the record to the destination. 3. If the record exist in the Destination and not in the Source then I will write to the transaction Log. Note: I am only concerned about updating one column in Destination which matches the only column in the source. Someone Please help??
View Replies !
Error: Could Not Create An Acceptable Cursor.
I'm trying to run a stored proc on a SQL 2005 SP1 box to return info to a SQL 2000 SP4 box, as a linked server. Both boxes have the latest service packs, and run Windows 2003 Server, again with the latest service packs. The error I get is: OLE DB provider "SQLNCLI" for linked server "192.168.0.126" returned message "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.".Msg 16955, Level 16, State 2, Line 1Could not create an acceptable cursor. The full script I am running is: CREATE procedure [dbo].[proc_AuditServer] as /* ** Auditing Script for SQL Servers. ** ** D Maxwell, June 2007 ** ** This script takes configuration and job status information ** and writes it to a designated logging server. I'll describe ** each section in detail, below. We write to the local box first, ** Then upload everything to the logging server. ** ** This is the SQL 2005 version. */ /* ** We want to know exactly what server this is, so ** we get the server name, instance name, as well as ** SQL Version, Edition, and Service Pack level. */ truncate table admin.dbo.sql_servers insert into admin.dbo.sql_servers select convert(varchar(15), serverproperty('ServerName')), convert(varchar(25), serverproperty('InstanceName')), convert(char(9), serverproperty('ProductVersion')), convert(varchar(4), serverproperty('ProductLevel')), convert(varchar(20), serverproperty('Edition')), getdate() /* ** Now, having that, we get the list of databases, ** as well as thier creation dates and file names. */ truncate table admin.dbo.databases insert into admin.dbo.databases select convert(varchar(15), serverproperty('ServerName')), dbid, name, crdate, filename from master..sysdatabases where dbid > 4 order by dbid /* ** We need to know how the server is configured, so we ** can compare it to a list of preferred configuration ** values, as well as the defaults. I cut this out of ** sp_configure. */ truncate table admin.dbo.server_config insert into admin.dbo.server_config select convert(varchar(15), serverproperty('ServerName')), name, config_value = c.value, run_value = master.dbo.syscurconfigs.value from master.dbo.spt_values, master.dbo.sysconfigures c, master.dbo.syscurconfigs where type = 'C' and number = c.config and number = master.dbo.syscurconfigs.config and ((c.status & 2 <> 0 ) OR (c.status & 2 = 0) ) order by lower(name) /* ** The next configuration item we want to get is the ** list of jobs that run on the server. We're looking ** specifically for backup and other maintenance jobs. ** (Which will hopefully be named appropriately...) ** We use Neil Boyle's job report script for this. ** My comments and changes prefaced by a 'DM:' */ truncate table admin.dbo.jobs insert into admin.dbo.jobs select convert(varchar(15), serverproperty('ServerName')), --DM: Needed since we'll have lots of servers reporting j.job_id, -- DM: More unique than a name. convert(varchar(22), j.name) as job_name, case freq_type -- Daily, weekly, Monthly when 1 then 'Once' when 4 then 'Daily' when 8 then 'Wk ' -- For weekly, add in the days of the week + case freq_interval & 2 when 2 then 'M' else '' end -- Monday + case freq_interval & 4 when 4 then 'Tu' else '' end -- Tuesday + case freq_interval & 8 when 8 then 'W' else '' end -- etc + case freq_interval & 16 when 16 then 'Th' else '' end + case freq_interval & 32 when 32 then 'F' else '' end + case freq_interval & 64 when 64 then 'Sa' else '' end + case freq_interval & 1 when 1 then 'Su' else '' end when 16 then 'Mthly on day ' + convert(varchar(2), freq_interval) -- Monthly on a particular day when 32 then 'Mthly ' -- The most complicated one, "every third Friday of the month" for example + case freq_relative_interval when 1 then 'Every First ' when 2 then 'Every Second ' when 4 then 'Every Third ' when 8 then 'Every Fourth ' when 16 then 'Every Last ' end + case freq_interval when 1 then 'Sunday' when 2 then 'Monday' when 3 then 'Tuesday' when 4 then 'Wednesday' when 5 then 'Thursday' when 6 then 'Friday' when 7 then 'Saturday' when 8 then 'Day' when 9 then 'Week day' when 10 then 'Weekend day' end when 64 then 'Startup' -- When SQL Server starts when 128 then 'Idle' -- Whenever SQL Server gets bored else 'Err' -- This should never happen end as schedule , case freq_subday_type -- FOr when a job funs every few seconds, minutes or hours when 1 then 'Runs once at:' when 2 then 'every ' + convert(varchar(3), freq_subday_interval) + ' seconds' when 4 then 'every ' + convert(varchar(3), freq_subday_interval) + ' minutes' when 8 then 'every ' + convert(varchar(3), freq_subday_interval) + ' hours' end as frequency -- All the subsrings are because the times are stored as an integer with no leading zeroes -- i.e. 0 means midnight, 13000 means half past one in the morning (01:30:00) , substring (right (stuff (' ', 1, 1, '000000') + convert(varchar(6),active_start_time), 6), 1, 2) + ':' + substring ( right (stuff (' ', 1, 1, '000000') + convert(varchar(6), active_start_time), 6) ,3 ,2) + ':' + substring ( right (stuff (' ', 1, 1, '000000') + convert(varchar(6),active_start_time), 6) ,5 ,2) as start_at ,case freq_subday_type when 1 then NULL -- Ignore the end time if not a recurring job else substring (right (stuff (' ', 1, 1, '000000') + convert(varchar(6), active_end_time), 6), 1, 2) + ':' + substring ( right (stuff (' ', 1, 1, '000000') + convert(varchar(6), active_end_time), 6) ,3 ,2) + ':' + substring ( right (stuff (' ', 1, 1, '000000') + convert(varchar(6), active_end_time), 6) ,5 ,2) end as end_at from msdb.dbo.sysjobs j, msdb.dbo.sysJobSchedules s, msdb.dbo.sysschedules c where j.job_id = s.job_id and s.schedule_id = c.schedule_id order by j.name, start_at /* ** Now that we know what jobs we have, let's find out ** how they did recently. */ truncate table job_status insert into job_status select convert(varchar(15), serverproperty('ServerName')), job_id, run_status, run_date, run_time, run_duration from msdb..sysjobhistory where step_name = '(job outcome)' -- The last 90 days' worth. and run_date > (select replace(convert(varchar(10), (getdate() - 90), 120), '-', '')) order by run_date desc /* ** If this server is already known to the audit server, ** we need to remove the existing data from the audit ** tables. */ declare @known bit set @known = (select count(*) from [192.168.0.126].AUDITDB.dbo.sql_servers where server_name = (select convert(varchar(15), serverproperty('servername')))) /* ** Now we remove the existing information from the audit tables, ** if need be. */ if @known = 1 begin delete from [192.168.0.126].AUDITDB.dbo.sql_servers where server_name = (select convert(varchar(15), serverproperty('ServerName'))) delete from [192.168.0.126].AUDITDB.dbo.databases where server_name = (select convert(varchar(15), serverproperty('ServerName'))) delete from [192.168.0.126].AUDITDB.dbo.server_config where server_name = (select convert(varchar(15), serverproperty('ServerName'))) delete from [192.168.0.126].AUDITDB.dbo.jobs where server_name = (select convert(varchar(15), serverproperty('ServerName'))) delete from [192.168.0.126].AUDITDB.dbo.job_status where server_name = (select convert(varchar(15), serverproperty('ServerName'))) end /* ** Finally, we upload the new info from here to the audit server. */ insert into [192.168.0.126].AUDITDB.dbo.sql_servers select * from admin.dbo.sql_servers insert into [192.168.0.126].AUDITDB.dbo.server_config select * from admin.dbo.server_config insert into [192.168.0.126].AUDITDB.dbo.databases select * from admin.dbo.databases insert into [192.168.0.126].AUDITDB.dbo.jobs select * from admin.dbo.jobs insert into [192.168.0.126].AUDITDB.dbo.job_status select * from admin.dbo.job_status This works fine for other boxes of the same service pack levels. I've already read KB302477, which doesn't appear to apply, since I'm already several revisions beyond that. I'm unable to duplicate this in test. Any ideas as to what I should look at next? Thanks. -D.
View Replies !
How To Use Cursor To Create Re-occuring Numbers?
SELECT pid, lname, visit_date, quantity FROM customer ORDER BY pid pid lname visit_date quantity ------------------------------------------- 23 wang 07/23/2006 100 23 wang 07/30/2006 140 23 wang 08/05/2006 130 23 wang 08/15/2006 135 23 wang 08/22/2006 110 34 linden 06/23/2006 99 34 linden 07/06/2006 110 34 linden 07/15/2006 120 34 linden 08/26/2006 99 How do I use cursor (or is there a better way) to create an additional column "index"? "Index" starts at 1 for every unique pid index pid lname visit_date quantity ---------------------------------------------------------- 1 23 wang 07/23/2006 100 2 23 wang 07/30/2006 140 3 23 wang 08/05/2006 130 4 23 wang 08/15/2006 135 5 23 wang 08/22/2006 110 1 34 linden 06/23/2006 99 2 34 linden 07/06/2006 110 3 34 linden 07/15/2006 120 4 34 linden 08/26/2006 99 Please let me know if I can explain the my question better. Thanks in advance
View Replies !
[SQL Server 2000] How Can I Create Cursor For A SQL Statement?
I have a SQL statement stored in a SQL varriable (after a lot of conditions) Code: declare @sql char(100) set @sql = 'select ma_kh, ten from _khang' Now, I want to create a cursor to recalculate some values I've tried: Code: declare cur_T cursor for exec(@sql) open cur_T but it doesn't work. Can I have another way to do that???
View Replies !
Not Able To Create Hash Table Inside Stored Proc Through &&"execute Sp_executesql @strQuery&&"
Hello, i need to create temporary table inside SP. i having one string variable @strQuery which contain dynamic query inside SP. i am executing that trhough execute sp_executesql @strQuery once query build. now instead of select query , i want to creat hash table. so i wrote : set @strQuery = "Select * into #tmp_tbl from table_name..." when i tried to execute it through execute sp_executesql @strQuery , its giving error 'Invalid object name '#tmp_tbl' If i removed Hash then it works fine. even for double Hash also its work fine. but i want hash table only as i want that table local to that user. Even direct execution of select statement without @strQuery works fine. but i want to execute @strQuery through execute sp_executesql @strQuery only as query is dynamic . please guide me how to do this? its very urgent for me. thanks in advance.
View Replies !
SQLDataSource Cntrl - FormView Cntrl - UPD Sproc And Sproc Debugger. I Dare Anyone To Figure This One Out.
I have attached the results of checking an Update sproc in the Sql database, within VSS, for a misbehaving SqlDataSource control in an asp.net web application, that keeps telling me that I have too many aurguments in my sproc compared to what's defined for parameters in my SQLdatasource control..... No rows affected. (0 row(s) returned) No rows affected. (0 row(s) returned) Running [dbo].[sp_UPD_MESample_ACT_Formdata] ( @ME_Rev_Nbr = 570858 , @A1 = No , @A2 = No , @A5 = NA , @A6 = NA , @A7 = NA , @SectionA_Comments = none , @B1 = No , @B2 = Yes , @B3 = NA , @B4 = NA , @B5 = Yes , @B6 = No , @B7 = Yes , @SectionB_Comments = none , @EI_1 = N/A , @EI_2 = N/A , @UI_1 = N/A , @UI_2 = N/A , @HH_1 = N/A , @HH_2 = N/A , @SHEL_1 = 363-030 , @SHEL_2 = N/A , @SUA_1 = N/A, @SUA_2 = N/A , @Cert_Period = 10/1/06 - 12/31/06 , @CR_Rev_Completed = Y ). No rows affected. (0 row(s) returned) @RETURN_VALUE = 0 Finished running [dbo].[sp_UPD_MESample_ACT_Formdata]. The program 'SQL Debugger: T-SQL' has exited with code 0 (0x0). And yet every time I try to update the record in the formview online... I get Procedure or function sp_UPD_MESample_ACT_Formdata has too many arguments specified. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Procedure or function sp_UPD_MESample_ACT_Formdata has too many arguments specified.Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. I have gone through the page code with a fine tooth comb as well as the sproc itself. I have tried everything I can think of, including creating a new page and resetting the fields, in case something got broken that I can't see. Does anyone have any tips or tricks or info that might help me? Thanks, SMA49
View Replies !
How To Get &&"CREATE ASSEMBLY Inside .NET CLR&&" Work ?
When the CLR function executes "CREATE ASSEMBLY" the following error is thrown. "Could not impersonate the client during assembly file operation." The CLR function is invoked from Service Broker internal activation stored procedure. "SELECT user_name()" returns dbo just before CREATE ASSEMBLY execution. SqlContext.WindowsIdentity.Name is "NT AUTHORITYSYSTEM" as the Data Engine runs with the LocalSystem account. How do I create a the necessary security context for "CREATE ASSEMBLY" to succeed ? Service Broker Queue activation with EXECUTE AS = "SELF", "OWNER", domain account or dbo, all result in the above error. The Service Broker assembly having the internal activation stored procedure is registered "unsafe".
View Replies !
EXEC Inside CASE Inside SELECT
I'm trying to execute a stored procedure within the case clause of select statement. The stored procedure returns a table, and is pretty big and complex, and I don't particularly want to copy the whole thing over to work here. I'm looking for something more elegant. @val1 and @val2 are passed in CREATE TABLE #TEMP( tempid INT IDENTITY (1,1) NOT NULL, myint INT NOT NULL, mybool BIT NOT NULL ) INSERT INTO #TEMP (myint, mybool) SELECT my_int_from_tbl, CASE WHEN @val1 IN (SELECT val1 FROM (EXEC dbo.my_stored_procedure my_int_from_tbl, my_param)) THEN 1 ELSE 0 FROM dbo.tbl WHERE tbl.val2 = @val2 SELECT COUNT(*) FROM #TEMP WHERE mybool = 1 If I have to, I can do a while loop and populate another temp table for every "my_int_from_tbl," but I don't really know the syntax for that. Any suggestions?
View Replies !
EXEC Of A Sproc Within Another Sproc
I'm sorta new with using stored procedures and I'm at a loss of how to achieve my desired result. What I am trying to do is retrieve a value from a table before it is updated and then use this original value to update another table. If I execute the first called sproc in query analyzer it does return the value I'm looking for, but I'm not really sure how to capture the returned value. Also, is there a more direct way to do this? Thanks, Peggy Sproc that is called from ASP.NET: ALTER PROCEDURE BP_UpdateLedgerEntry ( @EntryLogID int, @ProjectID int, @NewCategoryID int, @Expended decimal(10,2) ) AS DECLARE@OldCategoryID int EXEC @OldCategoryID = BP_GetLedgerCategory @EntryLogID UPDATE BP_EntryLog SET ProjectID = @ProjectID, CategoryID = @NewCategoryID, Expended = @Expended WHERE EntryLogID = @EntryLogID EXEC BP_UpdateCategories @ProjectID, @NewCategoryID, @Expended, @OldCategoryID Called Sprocs: ********************************************* BP_GetLedgerCategory ********************************************* ALTER PROCEDURE BP_GetLedgerCategory ( @EntryLogID int ) AS SELECT CategoryID FROM BP_EntryLog WHERE EntryLogID = @EntryLogID RETURN ********************************************* BP_UpdateCategories ********************************************* ALTER PROCEDURE BP_UpdateCategories ( @ProjectID int, @NewCategoryID int, @Expended decimal(10,2), @OldCategoryID int ) AS UPDATE BP_Categories SET CatExpended = CatExpended + @Expended WHERE ProjectID = @ProjectID AND CategoryID = @NewCategoryID UPDATE BP_Categories SET CatExpended = CatExpended - @Expended WHERE ProjectID = @ProjectID AND CategoryID = @OldCategoryID
View Replies !
Exec Sproc In Sproc
create procedure dbo.GetZipID( @City varchar(30), @State char(2), @Zip5 char(6)) as DECLARE @CityID integer declare @StateID integer declare @ZipID integer set @ZipID=2 set @Zip5=lTrim(@Zip5) if @Zip5<>'' SET @ZIPID = (select Min(lngZipCodeID) AS ZipID from ZipCodes where strZipCode=@Zip5) if @ZipID is null set @CityID= EXEC GetCityID(@City); set @StateID= EXEC GetStateID(@State); insert into ZipCodes(strZipCode,lngStateID,lngCityID) values(@Zip5,@StateID,@CityID) if @@ERROR = 0 SET @ZIPID = @@Identity select @ZIPID GetCityID and GetStateID are two stored procs, how do I execute those two stored procs in the above stored proc? I mean what is the syntax?? Tks
View Replies !
Differentiate Between Whether Stored Procedure A Is Executed Inside Query Analyzer Or Executed Inside System Application Itself.
Just wonder whether is there any indicator or system parameters that can indicate whether stored procedure A is executed inside query analyzer or executed inside application itself so that if execution is done inside query analyzer then i can block it from being executed/retrieve sensitive data from it? What i'm want to do is to block someone executing stored procedure using query analyzer and retrieve its sensitive results. Stored procedure A has been granted execution for public user but inside application, it will prompt access denied message if particular user has no rights to use system although knew public user name and password. Because there is second layer of user validation inside system application. However inside query analyzer, there is no way control execution of stored procedure A it as user knew the public user name and password. Looking forward for replies from expert here. Thanks in advance. Note: Hope my explaination here clearly describe my current problems.
View Replies !
Dynamic Cursor Versus Forward Only Cursor Gives Poor Performance
Hello,I have a test database with table A containing 10,000 rows and a tableB containing 100,000 rows. Rows in B are "children" of rows in A -each row in A has 10 related rows in B (ie. B has a foreign key to A).Using ODBC I am executing the following loop 10,000 times, expressedbelow in pseudo-code:"select * from A order by a_pk option (fast 1)""fetch from A result set""select * from B where where fk_to_a = 'xxx' order by b_pk option(fast 1)""fetch from B result set" repeated 10 timesIn the above psueod-code 'xxx' is the primary key of the current Arow. NOTE: it is not a mistake that we are repeatedly doing the Aquery and retrieving only the first row.When the queries use fast-forward-only cursors this takes about 2.5minutes. When the queries use dynamic cursors this takes about 1 hour.Does anyone know why the dynamic cursor is killing performance?Because of the SQL Server ODBC driver it is not possible to havenested/multiple fast-forward-only cursors, hence I need to exploreother alternatives.I can only assume that a different query plan is getting constructedfor the dynamic cursor case versus the fast forward only cursor, but Ihave no way of finding out what that query plan is.All help appreciated.Kevin
View Replies !
Could Not Complete Cursor Operation Because The Set Options Have Changed Since The Cursor Was Declared.
I'm trying to implement a sp_MSforeachsp howvever when I call sp_MSforeach_worker I get the following error can you please explain this problem to me so I can over come the issue. Msg 16958, Level 16, State 3, Procedure sp_MSforeach_worker, Line 31 Could not complete cursor operation because the set options have changed since the cursor was declared. Msg 16958, Level 16, State 3, Procedure sp_MSforeach_worker, Line 32 Could not complete cursor operation because the set options have changed since the cursor was declared. Msg 16917, Level 16, State 1, Procedure sp_MSforeach_worker, Line 153 Cursor is not open. here is the stored procedure: Alter PROCEDURE [dbo].[sp_MSforeachsp] @command1 nvarchar(2000) , @replacechar nchar(1) = N'?' , @command2 nvarchar(2000) = null , @command3 nvarchar(2000) = null , @whereand nvarchar(2000) = null , @precommand nvarchar(2000) = null , @postcommand nvarchar(2000) = null AS /* This procedure belongs in the "master" database so it is acessible to all databases */ /* This proc returns one or more rows for each stored procedure */ /* @precommand and @postcommand may be used to force a single result set via a temp table. */ declare @retval int if (@precommand is not null) EXECUTE(@precommand) /* Create the select */ EXECUTE(N'declare hCForEachTable cursor global for SELECT QUOTENAME(SPECIFIC_SCHEMA)+''.''+QUOTENAME(ROUTINE_NAME) FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = ''PROCEDURE'' AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(SPECIFIC_SCHEMA)+''.''+QUOTENAME(ROUTINE_NAME)), ''IsMSShipped'') = 0 ' + @whereand) select @retval = @@error if (@retval = 0) EXECUTE @retval = [dbo].sp_MSforeach_worker @command1, @replacechar, @command2, @command3, 0 if (@retval = 0 and @postcommand is not null) EXECUTE(@postcommand) RETURN @retval GO example useage: EXEC sp_MSforeachsp @command1="PRINT '?' GRANT EXECUTE ON ? TO [superuser]" GO
View Replies !
Join Cursor With Table Outside Of Cursor
part 1 Declare @SQLCMD varchar(5000) DECLARE @DBNAME VARCHAR (5000) DECLARE DBCur CURSOR FOR SELECT U_OB_DB FROM [@OB_TB04_COMPDATA] OPEN DBCur FETCH NEXT FROM DBCur INTO @DBNAME WHILE @@FETCH_STATUS = 0 BEGIN SELECT @SQLCMD = 'SELECT T0.CARDCODE, T0.U_OB_TID AS TRANSID, T0.DOCNUM AS INV_NO, ' + + 'T0.DOCDATE AS INV_DATE, T0.DOCTOTAL AS INV_AMT, T0.U_OB_DONO AS DONO ' + + 'FROM ' + @DBNAME + '.dbo.OINV T0 WHERE T0.U_OB_TID IS NOT NULL' EXEC(@SQLCMD) PRINT @SQLCMD FETCH NEXT FROM DBCur INTO @DBNAME END CLOSE DBCur DEALLOCATE DBCur Part 2 SELECT T4.U_OB_PCOMP AS PARENTCOMP, T0.CARDCODE, T0.CARDNAME, ISNULL(T0.U_OB_TID,'') AS TRANSID, T0.DOCNUM AS SONO, T0.DOCDATE AS SODATE, SUM(T1.QUANTITY) AS SOQTY, T0.DOCTOTAL - T0.TOTALEXPNS AS SO_AMT, T3.DOCNUM AS DONO, T3.DOCDATE AS DO_DATE, SUM(T2.QUANTITY) AS DOQTY, T3.DOCTOTAL - T3.TOTALEXPNS AS DO_AMT INTO #MAIN FROM ORDR T0 JOIN RDR1 T1 ON T0.DOCENTRY = T1.DOCENTRY LEFT JOIN DLN1 T2 ON T1.DOCENTRY = T2.BASEENTRY AND T1.LINENUM = T2.BASELINE AND T2.BASETYPE = T0.OBJTYPE LEFT JOIN ODLN T3 ON T2.DOCENTRY = T3.DOCENTRY LEFT JOIN OCRD T4 ON T0.CARDCODE = T4.CARDCODE WHERE ISNULL(T0.U_OB_TID,0) <> 0 GROUP BY T4.U_OB_PCOMP, T0.CARDCODE,T0.CARDNAME, T0.U_OB_TID, T0.DOCNUM, T0.DOCDATE, T3.DOCNUM, T3.DOCDATE, T0.DOCTOTAL, T3.DOCTOTAL, T3.TOTALEXPNS, T0.TOTALEXPNS my question is, how to join the part 1 n part 2? is there posibility?
View Replies !
Client Side Cursor Vs Sever Side Cursor?
I having a difficult time here trying to figure out what to do here.I need a way to scroll through a recordset and display the resultswith both forward and backward movement on a web page(PHP usingADO/COM)..I know that if I use a client side cursor all the records get shovedto the client everytime that stored procedure is executed..if thisdatabase grows big wont that be an issue?..I know that I can set up a server side cursor that will only send therecord I need to the front end but..Ive been reading around and a lot of people have been saying never touse a server side cursor because of peformance issues.So i guess im weighing network performance needs with the client sidecursor vs server performance with the server side cursor..I am reallyconfused..which one should I use?-Jim
View Replies !
SQL Sproc Help
I am trying to design a stored procedure to list out all of the unique software items that have been approved. There are multiple tables involved: CISSoftware, Software, Manufacturers, SoftwareTypes. Despite putting DISTINCT, I am still receiving rows of records where the software title (the title field) is a duplicate. Why is this query not working? Am I overlooking something? SELECT DISTINCT CISSoftware.SoftwareID, Software.Title, Manufacturers.ManufacturerID, Manufacturers.ManufacturerName, SoftwareTypes.SoftwareTypeID, SoftwareTypes.Type FROM CISSoftware, Software, Manufacturers, SoftwareTypes WHERE CISSoftware.SoftwareID = Software.SoftwareID AND Software.ManufacturerID = Manufacturers.ManufacturerID AND Software.SoftwareTypeID = SoftwareTypes.SoftwareTypeID
View Replies !
Need Help With An Sproc
This sproc seems to be way over my head. First off, let's start with the scenario. I have two tables. tblInventory and tblTempCart. Each contain an ItemID and Quantity. I need an sproc that will loop through the rows in tblTempCart and sum the quantity of each ItemID. Then, it needs to update the quantity in tblInventory based on what has been ordered for that ItemID. What I have tried thus far: UPDATE dbo.[4HCamp_tblStoreInventory]SET Quantity = Quantity - (SELECT SUM(dbo.[4HCamp_tblStoreTempCart].Quantity) AS Quantity FROM dbo.[4HCamp_tblStoreTempCart] WHERE dbo.[4HCamp_tblStoreTempCart].ItemID = dbo.[4HCamp_tblStoreInventory].ItemID) This works other than if the ItemID doesn't exist in tblTempCart, then it updates the quantity in tblInventory to NULL instead of retaining it's current value. I have no experience with looping in sql so any help will be greatly appreciated. Thanks! Amanda
View Replies !
Sproc Seems To Run Twice Instead Of Once...
I have tried to mix this around every way I can think of but the procedure inserts two rows instead of one. You will notice that I specify two commands/sprocs. I did that as part of my trying everything. when it was one command/sproc it did the same thing... What am I doing wrong? Please Help! :) ___________________ SPROC: ___________________ CREATE PROCEDURE dbo.sp_addMembershipRole @INCID Int AS declare @literal NVarChar (10) SET @literal = 'RTRListing' INSERT INTO dbo.RTR_memberPermissions ([memberID], [Role]) VALUES (@INCID, @literal) GO ___________________ CODE: ___________________ using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Security.Cryptography; using System.Web.Security; namespace admin { /// <summary> /// Summary description for createMembership. /// </summary> public class createMembership : System.Web.UI.Page { protected System.Web.UI.WebControls.RequiredFieldValidator Vusername; protected System.Web.UI.WebControls.RequiredFieldValidator Vpassword; protected System.Web.UI.WebControls.RequiredFieldValidator Vretype; protected System.Web.UI.WebControls.TextBox username; protected System.Web.UI.WebControls.TextBox password; protected System.Web.UI.WebControls.TextBox retype; protected System.Web.UI.WebControls.Label lblError; protected System.Web.UI.WebControls.Label lblDate; protected System.Web.UI.WebControls.Button btnAdd; private void Page_Load(object sender, System.EventArgs e) { if(! Page.IsPostBack) { string StrContactID = Request.QueryString["CID"].ToString(); Session["CID"]= StrContactID; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion public void btnAdd_Click(object sender, System.EventArgs e) { int intContactID; string StrCID = Session["CID"].ToString(); intContactID= Int32.Parse(StrCID); if(password.Text != retype.Text) { lblError.Text = "Retyping of your desired password did not match. Please try again."; return; } string pwdSalt = CreateSalt(5); string pwd = password.Text; string pwdHash = CreatePasswordHash(pwd, pwdSalt); string connStr= "server=****; uid=****; pwd=****; database=****"; string cmdStr= "sp_addMembershipUandP"; string cmd2Str= "sp_addMembershipRole"; SqlConnection CONN = new SqlConnection(connStr); CONN.Open(); SqlCommand cmd = new SqlCommand(cmdStr, CONN); cmd.CommandType = CommandType.StoredProcedure; SqlCommand cmd2= new SqlCommand(cmd2Str, CONN); cmd2.CommandType = CommandType.StoredProcedure; SqlParameter param; param = cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50); param.Value = username.Text; param = cmd.Parameters.Add("@password", SqlDbType.NVarChar, 50); param.Value = pwdHash; param = cmd.Parameters.Add("@salt", SqlDbType.NVarChar, 50); param.Value = pwdSalt; param = cmd.Parameters.Add("@CID", SqlDbType.Int, 4); param.Value = intContactID; SqlParameter param2; param2 = cmd2.Parameters.Add("@INCID", SqlDbType.Int, 4); param2.Value = intContactID; cmd.ExecuteNonQuery(); cmd2.ExecuteNonQuery(); CONN.Close(); return; } private static string CreateSalt(int size) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[size]; rng.GetBytes(buff); return Convert.ToBase64String(buff); } private static string CreatePasswordHash(string pwd, string salt) { string saltAndPwd = String.Concat(pwd, salt); string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "SHA1"); return hashedPwd; } } }
View Replies !
Help On Using LIKE In Sproc
hi all, I'm trying to learn using sproc in ASP.NET, but ran into problems I couldn't solve. Here're the details My Table (JournalArticle) ArticleID - int (PK) ArticleTitle - varchar ArticleContent - text I could run a normal sql string against the table itself in ASP.NET and got the results I expect. but when using a sproc, i couldn't get anything The sproc CREATE PROCEDURE dbo.sp_ArticleSearch(@srch text) AS SELECT ArticleID, ArticleTitle, ArticleContent FROM dbo.JournalArticle WHERE (ArticleAbstract LIKE @srch) GO After reading some of the threads here, I experimented by changing ArticleContent and @srch to type varchar, still no luck, it's not returning anything. I think the problem is when i set the value of @srch (being new at this, I could be seriously wrong though), like this: prmSearch.ParameterName = "@srch" prmSearch.SqlDbType = SqlDbType.Text prmSearch.Value = Request.Form("txtSearch") My original string looks like this strSQL = "SELECT * FROM JournalArticle WHERE (ArticleContent LIKE '%" & Request.Form("txtSearch") & "%')" What am I doing wrong?? Thanks in advance for any help.
View Replies !
Sproc In A Sproc
create procedure GetAddress(@Addr1 varchar(40), @Addr2 varchar(40), @City varchar(30), @State char(2), @Zip5 char(6), @Zip4 smallint) as begin declare @ZipID integer declare @AddrID integer set @AddrID=1 if lTrim(@Addr1)<>'' EXEC @ZipID= dbo.GetZipID(@City,@State,@Zip5) set @AddrID = (select Min(lngAddrID) from dbo.Addrs where lngZipCodeID=@ZipID and Address1=@Addr1 and Address2=@Addr2) return(@AddrID) end GO In the above sproc I m trying to call another sproc GetZipID . Its giving me an error stating that "Incorrect syntax near @City. " Can you help me out? The same syntax works for passing one variable but not for three. FYI this is the other sproc CREATE PROCEDURE dbo.GetZipID(@City varchar(30), @State char(2), @Zip5 char(6)) AS BEGIN DECLARE @CityID integer DECLARE @StateID integer DECLARE @ZipID integer SET @ZipID=2 set @Zip5=lTrim(@Zip5) if @Zip5<>'' SET @ZIPID = (select Min(lngZipCodeID) AS ZipID from ZipCodes where strZipCode=@Zip5) if @ZipID is null EXEC @CityID = dbo.GetCityID @City EXEC @StateID = dbo.GetStateID @State insert into ZipCodes(strZipCode,lngStateID,lngCityID) values(@Zip5,@StateID,@CityID) if @@ERROR = 0 SET @ZIPID = @@Identity Return @ZipID print @ZIPID END GO Thx in advance
View Replies !
Sproc This!
ha ha , havent used sql serv in years, and having trouble wit me sprocet! What devilish deed did i do? Use Contacts GO CREATE PROC MaserIn @entreddatetime= GETDATE(), @initialsvarchar(2)=Null, @Vendorvarchar(50), @CkNovarchar(20), @expTypevarchar(15), @ckDatedatetime, @ckAmtmoney, @mIdintOUTPUT AS INSERT INTO [Contacts].[dbo].[Master]( [entered], [initials], [Vendor], [CkNo], [expType], [ckDate], [ckAmt]) VALUES(@entered, @initials, @Vendor, @CkNo, @expType, @ckDate, @ckAmt) SELECT @mID=@@iDENTITY
View Replies !
Is It Possible To Do This In A Sproc
Hi. I wanted to know if its possible to do this in a sproc. if you want to hide the column that has no data, I suggest you to handle these works in your data accessing modular. For example, if you check one of your column is empty, just remove the column in your record set, so the column would not show in the report. If yes how can i do it.. Any help will be appreciated. Regards Karen
View Replies !
Help Needed With This Sproc
Hi, I am trying to Implement Multi parameter... If i give NULL it works fine but if i give '7,4' I get this error message Msg 102, Level 15, State 1, Line 18 Incorrect syntax near '17'. This is my sproc ALTER Procedure [dbo].[usp_GetOrdersByOrderDate] @ClientId nvarchar(max)= NULL, @StartDate datetime, @EndDate datetime AS Declare @SQLTEXT nvarchar(max) If @ClientId IS NULL Begin Select o.OrderId, o.OrderDate, o.CreatedByUserId, c.LoginId, o.Quantity, o.RequiredDeliveryDate, cp.PlanId, cp.ClientPlanId FROM [Order] o Inner Join ClientPlan cp on o.PlanId = cp.PlanId Inner Join ClientUser c on o.CreatedByUserId = c.UserId WHERE --cp.ClientId = @ClientId --AND o.OrderDate BETWEEN @StartDate AND @EndDate ORDER BY o.OrderId DESC END ELSE BEGIN SELECT @SQLTEXT = 'Select o.OrderId, o.OrderDate, o.CreatedByUserId, c.LoginId, o.Quantity, o.RequiredDeliveryDate, cp.PlanId, cp.ClientPlanId FROM [Order] o Inner Join ClientPlan cp on o.PlanId = cp.PlanId Inner Join ClientUser c on o.CreatedByUserId = c.UserId WHERE cp.ClientId in (' + @ClientId + ') AND o.OrderDate BETWEEN ' + Convert(varchar,@StartDate) + ' AND ' + convert(varchar, @EndDate) + ' ORDER BY o.OrderId DESC' execute (@SQLTEXT) END any help will be appreciated. Regards Karen
View Replies !
Can't Get SProc To Work
HiI can't seem to get this procedure to work correctly. Here's my code:DECLARE @PropertyDetails nvarchar (6)Select @PropertyDescription = PropertyDescription from Property whereApplicationID = @applicationidIf @PropertyDescription is not null or @PropertyDescription <> ''BeginIf (select isnumeric(PropertyDescription) from Property where ApplicationID =@applicationid) = 1INSERT INTO #errors VALUES (1410,@ApplicationID, 0, 'Y')ELSEINSERT INTO #errors values (1410, @ApplicationID, 0, 'N')EndI am trying to bring up an error advising users not to capture alphabets in afield called Property Description.I need to bring up the error from the #ERRORS table with the rule number 1410.My Syntax checks successful, but my error does not come up for the users. AmI missing something?Thanks for any help at all, guys.Driesen Pillay--Message posted via SQLMonster.comhttp://www.sqlmonster.com/Uwe/Forum...eneral/200508/1
View Replies !
Trouble With SPROC
Hi guysI having trouble with this sproc. I get the following error when testing:Server: Msg 245, Level 16, State 1, Procedure UTL_CompletenessCheckLoan, Line231Syntax error converting the varchar value 'danwet w125 ' to a column of datatype int.I have declared @Sellername as Varchar. Please can someone tell me what I'mdoing wrong? All it needs to do is return the 'Y' value if there are numericsin the sellername.declare @sellername varchar(40),@applicationid INTselect @sellername = sellername from Seller where ApplicationId =@ApplicationIdIf @sellername is not null or @sellername <> ''beginif (select isnumeric(Sellername) from seller where ApplicationId =@ApplicationId) = 1select 'Y'ELSEselect 'N'endThanks for any helpDriesen--Message posted via SQLMonster.comhttp://www.sqlmonster.com/Uwe/Forum...eneral/200509/1
View Replies !
How To Quit An Sproc
HiI am doing a check and on failing, i have a raiseerror command.I was assuming, once proc reaches raiseerror, it would stop the proc,but i see that the proc gives me an error message, but continues torun thru all the rest of the steps after raiseerror.how do i make the proc quit after reading raiseerror, only thrulabels ?IF @CheckIFFileHasOnlyOneOutputType 1BEGINRAISERROR ('Process Stopped. Input xls file is invalid, as it has morethan one output type specified in the OutputType Column', 16, 1)END--more proc steps are here ...Thanks in advance :RS
View Replies !
Tidying Up Of Sproc
HiI've written this sproc. Can any one suggest any optimisations to themain query and its sub-queries please? Truncated DDL afterCREATE PROCEDURE dbo.spGetUnbilledInfoByClient(@ClientID varchar(5),@Sort int = 0,@Dir int = 0) ASSET NOCOUNT ON-- The Main QuerySELECT mmatter, mdesc1, tkfirst + ' ' + tklast AS Contact,CONVERT(varchar(10), mopendt, 103) As [Date], CONVERT(DECIMAL(18,2),tTime.Cost) AS COST, tTime.Hours, tDisbursements.DisbursementsFROM matterINNER JOIN timekeep ON mbillaty = timekeep.tkinitlEFT JOIN (SELECT cmatter, SUM(Disbursements) AS Disbursements FROM (SELECT dbo.cost.cmatter,CASE WHEN dbo.cost.cauth = 'SO' OR dbo.cost.cauth = 'CF'THEN dbo.cost.cbillamt * 1.175ELSEdbo.cost.cbillamtEND AS DisbursementsFROM dbo.costWHERE (dbo.cost.cstatus = 'b') AND (dbo.cost.cinvoice IS NULL) AND(LEFT(dbo.cost.cmatter, 5) = @ClientID)) AS costsGROUP BY cmatter) AS tDisbursementsON dbo.matter.mmatter = tDisbursements.cmatterINNER JOIN(SELECT dbo.timecard.tmatter, SUM(dbo.timecard.tbillhrs) AS Hours,SUM(dbo.timecard.tbilldol) AS CostFROM dbo.timecard JOIN dbo.batch ON dbo.timecard.tbatch =dbo.batch.bbatchWHERE (dbo.timecard.tinvoice IS NULL)AND (dbo.timecard.tstatus = 'b')AND (LEFT(dbo.timecard.tmatter, 5) = @ClientID)AND (dbo.timecard.tbilldt IS NULL)AND ( NOT dbo.batch.bfindt IS NULL)GROUP BY tmatter) AS tTimeON dbo.matter.mmatter = tTime.tmatter--Sort (see http://www.sqlteam.com/forums/topic...942&whichpage=3)ORDER BYCASE -- numeric fieldsWHEN @Sort = 4 AND @Dir = 0THEN tTime.CostWHEN @Sort = 5 AND @Dir = 0THEN tTime.HoursWHEN @Sort = 6 AND @Dir = 0THEN tDisbursements.DisbursementsEND DESC,CASE -- datetimeWHEN @Sort = 0 AND @Dir = 0THEN mopendtWHEN @Sort = 3 AND @Dir = 0THEN mopendtEND DESC,CASE -- character fieldsWHEN @Sort = 1 AND @Dir = 0THEN mdesc1WHEN @Sort = 2 AND @Dir = 0THEN tkfirst + ' ' + tklastEND DESC,-- ASCCASE -- numeric fieldsWHEN @Sort = 4 AND @Dir = 1THEN tTime.CostWHEN @Sort = 5 AND @Dir = 1THEN tTime.HoursWHEN @Sort = 6 AND @Dir = 1THEN tDisbursements.DisbursementsEND ASC,CASE -- datetimeWHEN @Sort = 0 AND @Dir = 1THEN mopendtWHEN @Sort = 3 AND @Dir = 1THEN mopendtEND ASC,CASE -- character fieldsWHEN @Sort = 1 AND @Dir = 1THEN mdesc1WHEN @Sort = 2 AND @Dir = 1THEN tkfirst + ' ' + tklastEND ASCGOCREATE TABLE [matter] ([mname] [varchar] (24) COLLATE Latin1_General_CI_AS NULL ,[mmatter] [varchar] (15) COLLATE Latin1_General_CI_AS NULL ,[mrtcode] [smallint] NULL ,[mdept] [varchar] (10) COLLATE Latin1_General_CI_AS NULL ,[mopendt] [datetime] NULL ,[mbillaty] [varchar] (8) COLLATE Latin1_General_CI_AS NULL ,[mdesc1] [varchar] (48) COLLATE Latin1_General_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [cost] ([cindex] [int] IDENTITY (1, 1) NOT NULL ,[cmatter] [varchar] (15) COLLATE Latin1_General_CI_AS NULL ,[camount] [money] NULL ,[cbilldt] [datetime] NULL ,[cbillamt] [money] NULL ,[cinvoice] [int] NULL ,[ccode] [varchar] (7) COLLATE Latin1_General_CI_AS NULL ,[cbatch] [int] NULL ,[cauth] [varchar] (10) COLLATE Latin1_General_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [costcode] ([cocode] [varchar] (7) COLLATE Latin1_General_CI_AS NULL ,[codesc1] [varchar] (48) COLLATE Latin1_General_CI_AS NULL) ON [PRIMARY]GOCREATE TABLE [timecard] ([tindex] [int] IDENTITY (1, 1) NOT NULL ,[tmatter] [varchar] (15) COLLATE Latin1_General_CI_AS NULL ,[ttk] [varchar] (8) COLLATE Latin1_General_CI_AS NULL ,[tbilldt] [datetime] NULL ,[tbillhrs] [decimal](16, 2) NULL ,[tbillrt] [decimal](16, 2) NULL ,[tbilldol] [money] NULL ,[tinvoice] [int] NULL ,[tcode] [varchar] (7) COLLATE Latin1_General_CI_AS NULL ,[tbatch] [int] NULL) ON [PRIMARY]GOCREATE TABLE [batch] ([bbatch] [int] IDENTITY (1, 1) NOT NULL ,[btype] [varchar] (2) COLLATE Latin1_General_CI_AS NULL ,[bfindt] [datetime] NULL ,[bop] [varchar] (8) COLLATE Latin1_General_CI_AS NULL ,[bper] [varchar] (4) COLLATE Latin1_General_CI_AS NULL ,[bpflag] [varchar] (1) COLLATE Latin1_General_CI_AS NULL ,[bdopen] [datetime] NULL ,[btothrs] [decimal](12, 2) NULL ,[btotdol] [money] NULL) ON [PRIMARY]GO
View Replies !
SPROC To Select Top N
hi all i need to design a SPROC which will return me top n rows from a table. like GetTopN 4, will give me top 4 tuples /** GetTopN To list top n rows Date - 05 July 2004 Yogesh Jangam */ IF EXISTS (SELECT name FROM sysobjects WHERE name = 'GetTopN' AND type = 'P') DROP PROCEDURE GetTopN GO /************************ Actual SP Code *********************************/ Create procedure GetTopN (@intN int) AS BEGIN SET NOCOUNT ON declare SELECT TOP @intN from Employee -- this part i am not able to write end is there a answer? Thanks
View Replies !
|