Slow Procedure Using View

Jul 20, 2005

Hi

I have a procedure that calls a view. The view is built with some outer
joins but it performs fine.

If I run in Query Analyzer

select count(*) from long_name_view
where name_id = 'AAA'

it returns instantly

The procedure has the same code. I juststripped down the code to narrow
the problem:

create or replace procedure my_name_proc
@nid VARCHAR(32)
AS

DECLARE
@nidkey_count INTEGER

select @nidkey_count = count(*)
from long_name_view
where name_id = @nid

print 'The count: ' + CAST(@nidkey_count as varchar)

GO



When I call in Query Analyzer:

exec my_name_proc 'AAA'

it takes a while to run, over 20 sec and the execution plan is
different. What is the reason that the same view is used in different
ways?

Thanks



*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

View 1 Replies


ADVERTISEMENT

Slow Performance Using A View.

Jan 31, 2000

Hello,

I have the same database on two different servers. One for production and one for testing. A view that I use runs in less than 2 seconds on the test system, but takes almost 2 minutes on the production server.

What I have noticed is on the test server the view will use an index. The production server ends up scanning a whole table. All indices are the same on both machines for the tables involved and I have updated the statistics. I even went through the process of creating a new table with its indices for the table that is being scanned. Both machines have had service pack 1 installed on them.

Any ideas?

View 1 Replies View Related

Slow MDB Linked View

Jul 23, 2005

I previously posted re. this, but thought I'd try again with a summary offacts.I have an Access 2000 MDB with a SQL Server 7 back end. There is a view thatis linked to the database via ODBC and has been in place for several yearswithout any performance problems.Recently I added a couple of fields to the output of the view, and it becamevery slow when scrolling. When just opened in the database window, thelinked view takes about a second to scroll down one screen. When opened inthe form (in Continuous Form view), it takes about 2-3 seconds. It used toscroll just about instantaneously.I tried removing the few fields I added to restore the view to its previousform, but it had no effect. The view was still much slower than it had been.The total number of records returned from the view is about 1300, so it'snot a large number of records. The view has about 25 fields.I found that when I link the view in the MDB without specifying a uniqueindex, it scrolls very quickly -- almost instantaneously. But when I specifythe unique index, it is slow. Since the view needs to be edited, it needsthe unique index defined.As noted, it's been in place for years, with a unique index defined, yetwithout the slowness. Any ideas as to what might have caused this and whatmight be done would be appreciated. I've included the SQL for the viewbelow.Thanks,NeilSQL FOR MAIN VIEW:SELECT INVTRY.[Index], INVTRY.TITLE, INVTRY.AUTHILL1,INVTRY.attFirstEdition, INVTRY.attSigned,ISNULL(INVTRY.attSignedPD, ' ') SignedCond, INVTRY.YRPUB,INVTRY.PRICE, INVTRY.Web, INVTRY.Status,INVTRY.WebStatusPending, INVTRY.ActivateDate,INVTRY.DeactivateDate, INVTRY.WebAddedBatchID,INVTRY.AllowDuplicate, INVTRY.WebAction,INVTRY.WebActionPending, INVTRY.DateModified,INVTRY.DateWebActionApplied, INVTRY.JIT, INVTRY.MImage,INVTRY.HImage, INVTRY.AdCode,CASE WHEN INVTRY.WebAddedBatchID IS NOT NULLTHEN - 1 ELSE 0 END AS OnWebFROM vwInventory_Dupes INNER JOIN(WebStatus INNER JOIN(INVTRY INNER JOINtabStatus ON INVTRY.Status = tabStatus.Status) ONWebStatus.WebStatus = INVTRY.Web) ON(vwInventory_Dupes.YearPub = INVTRY.YRPUB) AND(vwInventory_Dupes.SignedCond = ISNULL(INVTRY.attSignedPD,' ')) AND (vwInventory_Dupes.Signed = INVTRY.attSigned) AND(vwInventory_Dupes.FirstEd = INVTRY.attFirstEdition) AND(vwInventory_Dupes.Author = INVTRY.AUTHILL1) AND(vwInventory_Dupes.TITLE = INVTRY.TITLE)WHERE (((tabStatus.ForWeb) = 1) AND ((WebStatus.IncludeDupe)= 1))SQL FOR vwInventory_Dupes:SELECT INVTRY.TITLE, INVTRY.AUTHILL1 Author,Cast(attFirstEdition AS tinyint) FirstEd,Cast(attSigned AS tinyint) Signed,ISNULL(INVTRY.attSignedPD, ' ') SignedCond,INVTRY.YRPUB YearPubFROM WebStatus INNER JOIN(INVTRY INNER JOINtabStatus ON INVTRY.Status = tabStatus.Status) ONWebStatus.WebStatus = INVTRY.WebWHERE (((tabStatus.ForWeb) = 1) AND ((WebStatus.IncludeDupe)= 1))GROUP BY INVTRY.TITLE, INVTRY.AUTHILL1,Cast(attFirstEdition AS tinyint), Cast(attSigned AS tinyint),ISNULL(INVTRY.attSignedPD, ' '), INVTRY.YRPUBHAVING (((COUNT(INVTRY.[INDEX])) > 1))

View 12 Replies View Related

View Executes Too Slow

Jun 22, 2006

i have written a query and created it as a view

when i run the query it takes less that 5 seconds to give results

but when i run the view it takes about a minute

can anyone help please, it keeps giving me time out errors

here is the query.


SELECT
MAX(B.Code) AS Code,
MAX( T.Description) AS Type,
MAX( WH.Description) AS Warehouse,
MAX(B.Barcode) AS Barcode,
MAX(B.BatchNo) AS BatchNo,
MAX(B.CustomField) AS CustomField,
MAX(B.Colour) AS Colour,
MAX(Q.Quality) AS Quality,
MAX(round( M.ConvFactor, 2, 2)) AS ConvFactor,
MAX( M.Multiply) AS Multiply,
MAX(CONVERT(VARCHAR(20),
round((B.BoughtQty + B.TransferQty + B.IssuedQty + B.ReturnedQty + B.AdjustmentQty), 2)))
+ ' ' + MAX( M.UoM) AS Available,
CASE WHEN MAX( M.Multiply) = 'M'
THEN MAX(CONVERT(VARCHAR(20),
round(((B.BoughtQty + B.TransferQty + B.IssuedQty + B.ReturnedQty + B.AdjustmentQty) * M.ConvFactor), 2)))
+ ' ' + MAX(M.AUoM)
ELSE max(CONVERT(Varchar(50),convert(float,
round(((B.BoughtQty + B.TransferQty + B.IssuedQty + B.ReturnedQty + B.AdjustmentQty) / M.ConvFactor), 2))) )
+ ' ' + MAX( M.AUoM)
END AS AvailableAlternative,
MAX(BC.Supplier) AS Supplier,
MAX( OD.SupplierCode) AS SupplierCode
FROM cvrbatches B
LEFT JOIN SciposA.dbo.cvrmaster M ON M.Code = B.Code
LEFT JOIN cvrbatchctrl BC ON B.Code = BC.Code
AND B.Type = BC.Type
AND B.BatchNo = BC.BatchNo
INNER JOIN SciposA.dbo.cvrwhcontrol WH ON WH.Warehouse = B.Warehouse
INNER JOIN SciposA.dbo.cvrtypes T ON T.CoverType = B.Type
INNER JOIN cvrquality Q ON Q.Code = B.Quality AND B.Type = Q.Type
LEFT JOIN SciposA.dbo.cvrgrndetail GD ON GD.BatchNo = B.BatchNo AND B.Warehouse = GD.Warehouse
LEFT JOIN SciposA.dbo.cvrorderdetails OD ON OD.OrderNo = GD.OrderNo AND OD.LineN = GD.LineN
GROUP BY B.Barcode

View 6 Replies View Related

Sql View Very Very Slow The First Run And Then Super Fast... Why?

Nov 2, 2007

Hi,
I have a query that takes 15minutes to run the first time after sql server start but then for subsequent querys is superfast (less than 10 secs).
Why? What could I do to speed up the first run?
Here is the source:



Code Block
SELECT Articoli.Articolo, Articoli.BarCodeVen, Articoli.Descri, Articoli.Merce, Articoli.CodIVA, Articoli.UMBase, Articoli.PrzBase, Articoli.Sconto1, Articoli.Sconto2,
Articoli.ScontoFormula, Articoli.Ricarico, Articoli.TipoArt, Articoli.CatMerc, Articoli.CatOmo, Articoli.CatProvv, Articoli.CntrprtVen, Articoli.CntrprtAcq,
Articoli.Dispniblta, Articoli.Vendita, Articoli.SiCli, Articoli.SiFor, Articoli.NotaPriv, Articoli.NotaPubb, Articoli.Immagine, Articoli.Produttore, Articoli.SiMatr,
Articoli.OldCodArt, Articoli.Disattivo, Articoli.CatProd, Articoli.SotCatProd, Articoli.EsplKit, Articoli.ScaricoCom, Articoli.ImmagLun, Articoli.DataModCS,
Articoli.ValorizPr, Articoli.Natura, Articoli.UMSecScelta, Articoli.SecScelta, Articoli.Acquisto, Articoli.CntConsumi, Articoli.NonMovimentabile,
Articoli.ProvAgente, Articoli.Taglia, Articoli.Colore, Articoli.CodArtNeutro, Articoli.Collezione, Articoli.Assortimento, Articoli.Centro,
Articoli.InibisciRicercaUnMis, Articoli.Commessa, Articoli.DescriTesto, Articoli.Disattivabile, Articoli.KwTipoArt, Articoli.KwTipoArtNeutro,
Articoli.KwNeutro, Articoli.KwCollezione, Articoli.KwLinea, Articoli.KwModello, Articoli.KwMateriale, Articoli.KwComposizione, Articoli.KwPosRiga,
Articoli.KwVarRiga, Articoli.KwPosColonna, Articoli.KwVarColonna, Articoli.KwPos3D, Articoli.KwVar3D, Articoli.KwGrpVarRiga, Articoli.KwGrpVarColonna,
Articoli.KwGrpVar3D, Articoli.KwEtiMan, Articoli.KwAssortimento, Articoli.KwGrpFormule, Articoli.KwSpecimen, KwVarArticolo.TipoVariante,
KwVarArticolo.Variante, KwVarArticolo.Posizione, KwVarArticolo.Categoria, KwVarArticolo.DescriVariante,
KwVarArticolo.P07009Descrizione1 AS Descrizione1, KwVarArticolo.P07009Descrizione2 AS Descrizione2, CatOmo.Descri AS CatOmoDescri,
KwModelli.Descri AS DescriModello, KwMateriali.Descri AS DescriMateriale, MFDBCompon_Tomaia2.DatoTecnico,
MFDBCompon_Tomaia2.DBPosColonna, MFDBCompon_Tomaia2.DBPos3D, MFDBCompon_Tomaia2.CompNeutro,
MFDBCompon_Tomaia2.CompVarRiga, Articoli_1.Descri AS DescriCompNeutro, MFKwVariantiRiga.DescriVariante AS DescriRigaCompo,
CatProvv.Descri AS CatProvvDescri, MFDBCompon_Tomaia3.CompNeutro AS CompNeutroT3,
MFDBCompon_Tomaia3.CompVarRiga AS CompVarrigaT3, Articoli_2.Descri AS DescriCompNeutroT3,
MFKwVariantiRiga_1.DescriVariante AS DescriRigaCompoT3, MFDBCompon_Acc1.CompNeutro AS CompNeutroAcc1,
MFDBCompon_Acc1.CompVarRiga AS CompVarRigaAcc1, Articoli_3.Descri AS DescriCompNeutroAcc1,
MFKwVariantiRiga_2.DescriVariante AS DescriRigaCompoAcc1, MFDBCompon_Acc2.CompNeutro AS CompNeutroAcc2,
MFDBCompon_Acc2.CompVarRiga AS CompVarRigaAcc2, Articoli_4.Descri AS DescriCompNeutroAcc2,
MFKwVariantiRiga_3.DescriVariante AS DescriRigaCompoAcc2, MFDBCompon_SottoP_Tallonet.CompNeutro AS CompNeutroSottop,
MFDBCompon_SottoP_Tallonet.CompVarRiga AS CompVarRigaSottop, MFDBCompon_SottoP_Tallonet.DescriCompNeutroSottop,
MFDBCompon_SottoP_Tallonet.DescriRigaCompoSottop, MFDBCompon_SottoP_Tallonet.DatoTecnico AS DatoTecnicoSottop,
MFDBCompon_RicSol.CompNeutro AS CompNeutroRicSol, MFDBCompon_RicSol.CompVarRiga AS CompVarRigaRicSol,
MFDBCompon_RicSol.DescriCompNeutroRicSol, MFDBCompon_RicSol.DescriRigaCompoRicSol,
MFDBCompon_Fodera.CompNeutro AS CompNeutroFodera, MFDBCompon_Fodera.CompVarRiga AS CompVarRigaFodera,
MFDBCompon_Fodera.DescriCompNeutroFodera, MFDBCompon_Fodera.DescriRigaCompoFodera, MFDBCompon_Forma.Descri AS DescriForma,
MFDBCompon_Tacco.Descri AS DescriTacco, MFVar3D_Pos1.DescriVariante AS Descri_Pos1, MFVar3D_Pos2.DescriVariante AS Descri_Pos2,
MFVar3D_Pos3.DescriVariante AS Descri_Pos3, MFVar3D_Pos4.DescriVariante AS Descri_Pos4, MFListinoP00New.Prz AS P00,
MFListinoP00New.InVigoreDa AS DataP00, MFListinoP05New.Prz AS P05, MFListinoP05New.InVigoreDa AS DataP05, MFListinoPUSANew.Prz AS PUSA,
MFListinoPUSANew.InVigoreDa AS DataPUSA,
CASE WHEN KwVarArticolo.P07009Descrizione2 <> '' THEN KwVarArticolo.P07009Descrizione2 ELSE CASE WHEN Articoli.CatProvv = '30SPORT' THEN Articoli.KwNeutro
+ KwVarArticolo.Variante + '.jpg' ELSE Articoli.KwNeutro + '.jpg' END END AS MFFoto, MFListinoRUSANew.Prz AS RUSA,
MFListinoRUSANew.InVigoreDa AS DataRUSA, MFListinoRITANew.Prz AS RITA, MFListinoRITANew.InVigoreDa AS DataRITA, ArtMerce.Fornitore
FROM Articoli INNER JOIN
KwVarArticolo ON Articoli.Articolo = KwVarArticolo.Articolo INNER JOIN
CatOmo ON Articoli.CatOmo = CatOmo.Categoria INNER JOIN
KwMateriali ON Articoli.KwModello = KwMateriali.KwModello AND Articoli.KwMateriale = KwMateriali.KwMateriale INNER JOIN
KwModelli ON Articoli.KwModello = KwModelli.KwModello AND Articoli.KwMateriale = KwModelli.KwMateriale LEFT OUTER JOIN
ArtMerce ON Articoli.Articolo = ArtMerce.Articolo LEFT OUTER JOIN
MFListinoRUSANew ON KwVarArticolo.Variante = MFListinoRUSANew.VarRiga AND Articoli.KwNeutro = MFListinoRUSANew.Neutro LEFT OUTER JOIN
MFListinoRITANew ON KwVarArticolo.Variante = MFListinoRITANew.VarRiga AND Articoli.KwNeutro = MFListinoRITANew.Neutro LEFT OUTER JOIN
MFListinoPUSANew ON KwVarArticolo.Variante = MFListinoPUSANew.VarRiga AND Articoli.KwNeutro = MFListinoPUSANew.Neutro LEFT OUTER JOIN
MFListinoP05New ON KwVarArticolo.Variante = MFListinoP05New.VarRiga AND Articoli.KwNeutro = MFListinoP05New.Neutro LEFT OUTER JOIN
MFListinoP00New ON Articoli.KwNeutro = MFListinoP00New.Neutro AND KwVarArticolo.Variante = MFListinoP00New.VarRiga LEFT OUTER JOIN
MFVar3D_Pos4 ON Articoli.KwNeutro = MFVar3D_Pos4.Articolo LEFT OUTER JOIN
MFVar3D_Pos3 ON Articoli.KwNeutro = MFVar3D_Pos3.Articolo LEFT OUTER JOIN
MFVar3D_Pos2 ON Articoli.KwNeutro = MFVar3D_Pos2.Articolo LEFT OUTER JOIN
MFVar3D_Pos1 ON Articoli.KwNeutro = MFVar3D_Pos1.Articolo LEFT OUTER JOIN
MFDBCompon_Forma ON KwVarArticolo.Variante = MFDBCompon_Forma.DBVarRiga AND
Articoli.Articolo = MFDBCompon_Forma.DBNeutro LEFT OUTER JOIN
MFDBCompon_Tacco ON KwVarArticolo.Variante = MFDBCompon_Tacco.DBVarRiga AND
Articoli.Articolo = MFDBCompon_Tacco.DBNeutro LEFT OUTER JOIN
MFDBCompon_Fodera ON KwVarArticolo.Variante = MFDBCompon_Fodera.DBVarRiga AND
Articoli.KwNeutro = MFDBCompon_Fodera.DBNeutro LEFT OUTER JOIN
MFDBCompon_RicSol ON KwVarArticolo.Variante = MFDBCompon_RicSol.DBVarRiga AND
Articoli.KwNeutro = MFDBCompon_RicSol.DBNeutro LEFT OUTER JOIN
MFDBCompon_SottoP_Tallonet ON KwVarArticolo.Variante = MFDBCompon_SottoP_Tallonet.DBVarRiga AND
Articoli.KwNeutro = MFDBCompon_SottoP_Tallonet.DBNeutro LEFT OUTER JOIN
MFDBCompon_Acc2 INNER JOIN
Articoli AS Articoli_4 ON MFDBCompon_Acc2.CompNeutro = Articoli_4.Articolo INNER JOIN
MFKwVariantiRiga AS MFKwVariantiRiga_3 ON MFDBCompon_Acc2.CompVarRiga = MFKwVariantiRiga_3.Variante ON
KwVarArticolo.Variante = MFDBCompon_Acc2.DBVarRiga AND Articoli.KwNeutro = MFDBCompon_Acc2.DBNeutro LEFT OUTER JOIN
MFDBCompon_Acc1 INNER JOIN
Articoli AS Articoli_3 ON MFDBCompon_Acc1.CompNeutro = Articoli_3.Articolo INNER JOIN
MFKwVariantiRiga AS MFKwVariantiRiga_2 ON MFDBCompon_Acc1.CompVarRiga = MFKwVariantiRiga_2.Variante ON
KwVarArticolo.Variante = MFDBCompon_Acc1.DBVarRiga AND Articoli.KwNeutro = MFDBCompon_Acc1.DBNeutro LEFT OUTER JOIN
MFDBCompon_Tomaia3 INNER JOIN
Articoli AS Articoli_2 ON MFDBCompon_Tomaia3.CompNeutro = Articoli_2.Articolo INNER JOIN
MFKwVariantiRiga AS MFKwVariantiRiga_1 ON MFDBCompon_Tomaia3.CompVarRiga = MFKwVariantiRiga_1.Variante ON
KwVarArticolo.Variante = MFDBCompon_Tomaia3.DBVarRiga AND Articoli.KwNeutro = MFDBCompon_Tomaia3.DBNeutro LEFT OUTER JOIN
CatProvv ON Articoli.CatProvv = CatProvv.Categoria LEFT OUTER JOIN
Articoli AS Articoli_1 INNER JOIN
MFDBCompon_Tomaia2 ON Articoli_1.Articolo = MFDBCompon_Tomaia2.CompNeutro INNER JOIN
MFKwVariantiRiga ON MFDBCompon_Tomaia2.CompVarRiga = MFKwVariantiRiga.Variante ON
KwVarArticolo.Variante = MFDBCompon_Tomaia2.DBVarRiga AND Articoli.KwNeutro = MFDBCompon_Tomaia2.DBNeutro
WHERE (Articoli.KwCollezione = @KwCollezione) AND (Articoli.KwLinea = @KwLinea) AND (KwVarArticolo.TipoVariante = 52559872) AND
(Articoli.CatProvv IN (@CatProvv)) AND (Articoli.Disattivo = '0') AND (KwVarArticolo.Disattivo = '0') AND (ArtMerce.Fornitore IN (@Fornitore)) OR
(Articoli.KwCollezione = @KwCollezione) AND (Articoli.KwLinea = @KwLinea) AND (KwVarArticolo.TipoVariante = 52559872) AND
(Articoli.CatProvv IN (@CatProvv)) AND (Articoli.Disattivo = '0') AND (KwVarArticolo.Disattivo = '0') AND ('ALL' IN (@Fornitore)) OR
(Articoli.KwCollezione = @KwCollezione) AND (Articoli.KwLinea = @KwLinea) AND (KwVarArticolo.TipoVariante = 52559872) AND (Articoli.Disattivo = '0')
AND (KwVarArticolo.Disattivo = '0') AND (ArtMerce.Fornitore IN (@Fornitore)) AND ('ALL' IN (@CatProvv)) OR
(Articoli.KwCollezione = @KwCollezione) AND (Articoli.KwLinea = @KwLinea) AND (KwVarArticolo.TipoVariante = 52559872) AND (Articoli.Disattivo = '0')
AND (KwVarArticolo.Disattivo = '0') AND ('ALL' IN (@CatProvv)) AND ('ALL' IN (@Fornitore))
ORDER BY Articoli.CatProvv, Articoli.CatOmo, Articoli.Articolo, KwVarArticolo.Posizione


Thank you!
Roberto

View 3 Replies View Related

SQL 2012 :: Indexed View On Replicated Server Is Very Slow

Sep 10, 2014

So we got ServerA.dbA and ServerB.dbB and looks like nobody thought about that MVew. IT works thru linked server now, so surely enough it sucks..

Then even more: we got piece of DW on ServerRep with replcicated pieces of ServerA and ServerB, how it works I asked: "Don't worry man, we took care of everything, go directly to ServerRep for everything..."

And I see that our MView sucks even deeper, practically 0 performance, I think what going on it's still hit that linked server between ServerA.dbA and ServerB.dbB on background.I still can use it on ServerRep WITH NOEXPAND hint, which means it was properly defined...

Can we have that scenario at all? Or we can replicate all Tables on ServerRep and then define/redefine this view directly on replicated server ?

View 4 Replies View Related

DB Engine :: Performance Tuning Temp DB Slow INSERT From VIEW

May 16, 2015

I am running A View that INSERTS into #Temp Table - On Only Certain Days the INSERT Speed into #tempDB is so slow.
 
Attached snapshot that shows after one minute so many few records are inserted - and it dosent happen every day somedays its very fast. 

View 3 Replies View Related

Calling A Stored Procedure From A View OR Creating A #tempTable In A View

Aug 24, 2007

Hi guys 'n gals,

I created a query, which makes use of a temp table, and I need the results to be displayed in a View. Unfortunately, Views do not support temp tables, as far as I know, so I put my code in a stored procedure, with the hope I could call it from a View....

I tried:

CREATE VIEW [qryMyView]
AS
EXEC pr_MyProc


and unfortunately, it does not let this run.

Anybody able to help me out please?

Cheers!

View 3 Replies View Related

Stored Procedure Too Slow

Apr 30, 2008

When the same code is executed in query analyzer it takes 2s instead of 20s when executing the sp. Any idea?

View 9 Replies View Related

Stored Procedure Runs Slow Only Sometimes

Jan 6, 2006

When i execute a stored procedure it generally takes about half a second to run but sometimes it takes 20 to 30 seconds.  I am the only one using the server so I know it is not due to other traffic.  I have looked at Profiler and nothing looks out of the ordinary.  Another observation is that the slow ones are always near eachother.  I will have about 10 fast executions and then 3 slow ones and then back to fast ones.  Has anyone seen anything like this before? 

View 5 Replies View Related

How To Simplify This Slow Stored Procedure

Jan 20, 2005

Dear Reader(s),

Is there anyway to write the following stored procedure without the loop so that it goes much faster? :confused:

----------------------------------------------------------------------------
use MJ_ReportBase
go
if exists(select 1 from sysobjects where type='P' and name='sp_Periode')
begin
drop procedure sp_Periode
end
go
create procedure sp_Periode
@start int
, @stop int
as
declare @x int

set @x = 0
set @x=@start

delete from tbl_periode

while (@x>=@stop)
begin

-- ---
-- ---
-- Create table tbl_inout
if exists(select 1 from sysobjects where type='U' and name='tbl_inout')
begin
drop table tbl_inout
end

select datetimestamp,accname,badgeid,personname,inoutreg into tbl_inout from WinXS..x18 where convert(varchar,datetimestamp,120)+' '+ltrim(str(id))+' '+ltrim(str(badgeid)) in
(select convert(varchar,max(datetimestamp),120)+' '+ltrim(str(max(id)))+' '+ltrim(str(badgeid)) as datetimestamp from WinXS..x18 where (accname='Kelder -1' or accname='Tnk Entree') and convert(varchar,datetimestamp,105)=convert(varchar ,getdate()-abs(@x),105) group by badgeid)
and badgeid>0
order by personname

-- ---
-- ---
-- Create table tbl_result

if exists(select 1 from sysobjects where type='U' and name='tbl_result')
begin
drop table tbl_result
end

-- ---
-- ---

select
convert(varchar,datetimestamp,105) 'DATUM'
, badgeid 'PAS'
, initials 'VOORNAAM'
, personname 'NAAM'
, convert(varchar,min(datetimestamp),108) 'MIN'
, convert(varchar,max(datetimestamp),108) 'MAX'
into
tbl_result
from
WinXS..x18
where
convert(varchar,datetimestamp,105)=convert(varchar ,getdate()-abs(@x),105)
and
accname in ('Kelder -1','Tnk Entree')
and badgeid>0
group by
convert(varchar,WinXS..x18.datetimestamp,105)
, badgeid
, initials
, personname
order by
initials
, personname asc
, convert(varchar,datetimestamp,105) asc

-- ---
-- ---
-- Rapportage tabel

insert into
tbl_periode
select
tbl_result.datum as DATUM
, ltrim(ltrim(rtrim(tbl_result.naam))+' '+ltrim(rtrim(isnull(tbl_result.voornaam,' ')))) as NAAM
, tbl_result.min as MIN
, tbl_result.max as MAX
, case tbl_inout.inoutreg when 1 then 'in' when 2 then 'out' else 'err' end as [IN/OUT]
, substring('00000',1,5-len(tbl_result.pas))+ltrim(str(tbl_result.pas)) as PAS
from
tbl_inout,tbl_result
where
tbl_result.datum+' '+tbl_result.max+' '+ltrim(str(tbl_result.pas))
= convert(varchar,tbl_inout.datetimestamp,105)+' '+convert(varchar,tbl_inout.datetimestamp,108)+' '+ltrim(str(badgeid))
order by
tbl_result.naam asc

-- ---
-- ---
--

set @x=@x-1
end
go

print 'Klaar!'
--------------------------------------------------------------------------

What it does is determining the minimum entry time and the maximum exiting time per day of people going true the main entrance of a building.

Many thanks in advance.
:)

View 3 Replies View Related

Slow Execution Of Stored Procedure

Jun 29, 2007

Hello,

I have a big problem with slow execution of stored procedure in SQL Server 2005 but I really don't understand the reason. I have a database with large table (about 400 million rows) and simple stored procedure to get data from that table (one select statement to select time and value columns).

Strange thing is that if I call that stored procedure from .net application (native SqlDataProvider) it takes about 6 seconds to execute but if I call the same procedure with the same parameters from within SQL Server Management Studio it takes only 25 milliseconds to execute!

I've noticed that from .net, procedure is called with binary data and in Management Studio sql script is executed so I've copied/pasted the script from Management Studio to .net code and again the same thing happens (6 seconds from .net and 25ms from Management Studio). I traced executions with SQL Profiler and everything seems to be identical for both applications except it takes much longer time for .net application.

Both SQL Server Management Studio and .net application are on the same machine and SQL Server is on another.

This is the query that when executed in Management Studio takes 25ms:

EXEC [dbo].[GetRawData] @pcu = N'DV_ZERJ_HEV1',@tag = N'MJERENO',@from = N'20070629 07:00:00',@to = N'20070629 08:00:00'

This is the same query in .net application code that takes 6 seconds to execute:

sqlCommand = new SqlCommand("EXEC [dbo].[GetRawData] @pcu = N'DV_ZERJ_HEV1',@tag = N'MJERENO',@from = N'20070629 07:00:00',@to = N'20070629 08:00:00'",sqlConnection);
sqlReader = sqlCommand.ExecuteReader();

At first I thought that Management Studio somehow caches results but if I change parameters of stored procedure it always takes less than 30ms to execute.
I really don't understand this. Please, help!

View 7 Replies View Related

Stored Procedure Running Slow In ADO.NET

Jan 9, 2008

We have a stored procedure which is running fine on a SQL server 2000 from Query Analyzer. However, when we try to execute the same stored procedure from ADO.NET in an executable, the execution is hung or takes extremely long. Does anyone have any ideas or suggestions about how it could happen and how to fix. thanks

View 22 Replies View Related

Stored Procedure - Page Load Slow

Jul 25, 2006

Hi all,
I have a webpage with a Datagrid that populates using a table adapter from a Stored procedure that exists in my SQL Database...If I run the Stored procedure in SQL Directly then it takes 20 Secs to return all records...If I run the webpage then it takes just over 20 Secs..
Great you say..But If I have the sorting option set in ASP.net and I click on a column to sort then off the page goes for another 20 secs to sort the data..
Is there a better way to do what I am doing here that will speed up the page load..
Ie..the data is returned once and then sorted...
Is it Better / Quicker for me to create a table using the stored procedure and link to this from the website..Updating the table every couple of minutes ?
Any advice please ?
Ray..

View 4 Replies View Related

Stored Procedure Run From ASP.NET Page Gets Very Slow Intermittently

Dec 5, 2006

I have developed a stored procedure that filters a view that is a union of several different tables. This provides status information for items across our warehouse management system. This system seems to work very well and normally processes results very quickly (< 3 seconds). However, occasionally (every few days) we begin to see timeouts on the query after 3 minutes of processing. I can watch this process in SQL Profiler and see that the query is timing out after 180 seconds, which is the timeout we have for the query within the DAL. When I copy the line from the SQL Profiler and execute it directly in SSMS, the query executes in less than 2 seconds. I first thought that somehow this had to do with execution plans, but when I try to reload the page again, which executes the query, it still times out. I did add a OPTION(KEEPFIXED PLAN) to the sproc, and that seemed to speed things up for the time, but I am not sure if this is even the problem and what the optimal solution would be. Any thoughts spring to mind?
 Thanks, Steve

View 3 Replies View Related

Slow Procedure While Checking Duplicate Records

Jun 21, 2001

hello friends


i m stuck up with a problem...actually i dont have much experience in database line....i m new to this line....i have recently joined the job & this problem is like a test of me....if i will be able to give the solution then everything is fine otherwise i will be fired & im not in a condition to leave this job as this is my first job in software development....i have got this chance with lots of difficulty....so please help me if u can...


the problem is....>> i m using a procedure to check the duplicatye records by using string comparison against address of persons..allover the country....

i m using SQL server 7.0
i have a single table(name of table is DATA) which contains 350000 records( i mean address entries) there are about 35 columns but i have to check duplicate records only against address field...for that first of all i remove special characters from the address field.....then i compare first 20 characters for duplicate entries...

for this i m generating another table(name of another table is RESULT)...

how the logic works...initially the data table contains the records but the result table is totally blank....first of all i pick first entry of address from DATA table then...check it with the entry in RESULT table if the entry exists... it compares the address if the record is same then it generates a refference of this address and make an entry....means a refference of that entry....(as far as very first record is concerned there will be no entry in the RESULT table so it will enter the address over there...then it picks up the second record...checks it in the RESULT table...now this record will be compared with the one & only entry in the RESULT table....if the entry is same then the refference will be entered... otherwise it will be entered as second record in the RESULT table....)

now where lies the problem.....initially the procedure is very fast.... but it gradually slows down .....because(when it checks the 10th record for duplication it compares the entry in RESULT table for 9 times only
*** similarly when it checks the 100th record it compares it for 99 times
*** similarly when it checks the 10000th record it compares it for 9999 times
so here lies the problem....

when it checks the 100000th record it gets dammm slow...
what i have get till now is that i have checked.....>>>>>
5000 records in 4 mins....
25000 records in 22 mins....
and
100000 records in 20 hours....(means initially its faster but it gradually slows down)
************************************************** ************************
here i m giving the code for the procedure......
************************************************** *************************


CREATE PROCEDURE pro1 as

SET NOCOUNT ON
Declare @IvgId as numeric(15)
Declare @Address as nvarchar(250)
Declare @AddressClean as nvarchar(250)
Declare @MaxLen as INT
Declare @Add as nvarchar(250)
Declare @Ic as int
Declare @FoundIvgId as numeric(15)
Declare @NewIvgId as numeric(15)

/* here 'N' is for keeping track for some system failures etc */

Declare CurData CURSOR forward_only FOR Select IvgId, Address From Data Where ProcessClean = 'N'

OPEN CurData

FETCH NEXT FROM CurData INTO @IvgId, @Address

WHILE @@FETCH_STATUS = 0
Begin
/*here i m doing string cleaning by removing special characcters */
Select @MaxLen = len(LTRIM(RTRIM(@Address)))
Select @Address = LOWER(@Address)
Select @Ic = 1
Select @AddressClean = ' '
While @Ic <= @MaxLen
/* here @MaxLen is the maximum length of the address field but i have to compare only first 20 characters */
Begin
Select @Add = Substring(@Address, @Ic, 1)

If ascii(@Add) > 47 AND ascii(@Add) <= 64 AND @Add <> ' '
Begin
Select @AddressClean = @AddressClean + @Add
End

If ascii(@Add) > 90 AND @Add <> ' '
Begin
Select @AddressClean = @AddressClean + @Add
End

Select @Ic = @Ic + 1
End

/* now we have removed special characters , for failure checking i m using this 'Y' */
Update Data Set AddressClean = @AddressClean, ProcessClean = 'Y'
Where IvgId = @IvgId

FETCH NEXT FROM CurData INTO @IvgId, @Address
End

PRINT 'Cleaning Done.............................'

Close CurData
Deallocate CurData

/* till now procedure doesnt take too much time & cleans all the 3 lack records in abt 40 mins but next part is giving trouble */

Declare CurData CURSOR FOR Select IvgId, Address, AddressClean From Data Where ProcessDup = 'N'
OPEN CurData

FETCH NEXT FROM CurData INTO @IvgId, @Address, @AddressClean
Select @NewIvgId = 100

WHILE @@FETCH_STATUS = 0
Begin

If EXISTS (Select IvgId From Result Where SubString(RTRIM(LTRIM(AdressClean)),1,20) = SubString(RTRIM(LTRIM(@AddressClean)),1,20))
Begin
Update Result Set DupIvgId = @IvgId Where SubString(RTRIM(LTRIM(AdressClean)),1,20) = SubString(RTRIM(LTRIM(@AddressClean)),1,20)
End

ELSE
Begin
Insert Into Result Values (@NewIvgId, @Address, @AddressClean,0)
Select @NewIvgId = @NewIvgId + 1
End

Update Data set ProcessDup = 'Y' Where IvgId = @IvgId
FETCH NEXT FROM CurData INTO @IvgId, @Address, @AddressClean
End

Close CurData
Deallocate CurData
SET NOCOUNT OFF

Print 'Done................................'

************************************************** **************************
now the procedure is over....now i m writing the SQL script of DATA & RESULT table
************************************************** ************************

CREATE TABLE [dbo].[DATA] (
[IVGID] [numeric](18, 0) NOT NULL ,
[Title] [varchar] (10) NULL ,
[FirstName] [varchar] (50) NULL ,
[MiddleName] [varchar] (10) NULL ,
[LastName] [varchar] (30) NULL ,
[Add1] [varchar] (150) NULL ,
[Add2] [varchar] (50) NULL ,
[Add3] [varchar] (50) NULL ,
[City] [varchar] (30) NULL ,
[State] [varchar] (30) NULL ,
[Country] [varchar] (20) NULL ,
[Pincode] [varchar] (10) NULL ,
[OffPhone] [varchar] (20) NULL ,
[OffFax] [varchar] (20) NULL ,
[ResPhone] [varchar] (20) NULL ,
[ResFax] [varchar] (20) NULL ,
[EMail] [varchar] (50) NULL ,
[Source] [varchar] (20) NULL ,
[MODEL] [varchar] (20) NULL ,
[PNCD] [varchar] (6) NULL ,
[DupKey] [decimal](18, 0) NULL ,
[Duplicate] [int] NULL ,
[HouseHoldID] [varchar] (50) NULL ,
[YearSlab] [varchar] (10) NULL ,
[CleanStatus] [int] NULL ,
[AddStatus] [int] NULL ,
[BatchNo] [varchar] (20) NULL ,
[ModelStatus] [int] NULL ,
[Month] [int] NULL ,
[Year] [int] NULL ,
[SapStatus] [int] NULL ,
[ErrCase] [int] NULL ,
[cmpCity] [varchar] (50) NULL ,
[Product] [varchar] (1) NULL ,
[cmpPinCode] [varchar] (6) NULL ,
[Address] [nvarchar] (250) NULL ,
[AddressClean] [nvarchar] (250) NULL ,
[DupIvgId] [numeric](18, 0) NULL ,
[ProcessClean] [nvarchar] (1) NULL ,
[ProcessDup] [nvarchar] (1) NULL
) ON [PRIMARY]
GO

/****** Object: Table [dbo].[DATA_TEST] Script Date: 15/06/2001 8:36:21 PM ******/
CREATE TABLE [dbo].[DATA_TEST] (
[IVGID] [numeric](18, 0) NOT NULL ,
[Address] [nvarchar] (50) NULL ,
[AddressClean] [nvarchar] (50) NULL ,
[DupIvgId] [numeric](18, 0) NULL ,
[ProcessClean] [nvarchar] (1) NULL ,
[ProcessDup] [nvarchar] (1) NULL
) ON [PRIMARY]
GO

so now i have given the whole description of my problem....i m eagerly waiting for reply......
if anybody can help....i will be very thankful.....
bye for now
Bhupinder singh

View 1 Replies View Related

Stored Procedure Works But Very Slow (was Optimization)

Mar 1, 2005

I have a big table A_newHistory (more than 2 million rows) with primary key fund_id + date_price . This table has to be updated every 2 hours from XML.
Every row in XML must be inserted or updated (if current id and date already exist in the table) in the A_newHistory.
The following procedure works but very slow...
How can I optimize that?

================================================== =======
CREATE PROCEDURE spSaveFundsAdjustedClose
@XML ntext
AS
DECLARE @fund_id int
DECLARE @date_price datetime
DECLARE @adj_closed float
DECLARE @XMLDoc int

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION

EXEC sp_xml_preparedocument @XMLDoc OUTPUT, @XML

DECLARE MutualFunds_Cursor CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
SELECT *
FROM OPENXML (@XMLDoc , '/xml/a', 1)
WITH ([id] INT,[date] datetime, price float)
OPEN MutualFunds_Cursor
FETCH NEXT FROM MutualFunds_Cursor
INTO @fund_id, @date_price, @adj_closed

WHILE @@FETCH_STATUS = 0
BEGIN
IF EXISTS (SELECT * FROM A_newHistory
WHERE id_fund = @fund_id AND date_price = @date_price)
BEGIN
UPDATE A_newHistory
SET adj_close = @adj_closed
WHERE id_fund = @fund_id AND date_price = @date_price
END
ELSE
BEGIN
INSERT INTO A_newHistory
VALUES(@fund_id, @date_price, @adj_closed)
END

IF @@Error <> 0
BEGIN
ROLLBACK TRANSACTION
SELECT -1
RETURN
END

FETCH NEXT FROM MutualFunds_Cursor
INTO @fund_id, @date_price, @adj_closed
END

EXEC sp_xml_removedocument @XMLDoc
CLOSE MutualFunds_Cursor
DEALLOCATE MutualFunds_Cursor

COMMIT TRANSACTION
SELECT 0
GO
================================================== =======

View 1 Replies View Related

Slow Stored Procedure - Easy Located But Wtf?

Jul 20, 2005

Hi,Plz, I need some info (SQL2000) :)A stored procedure is like this:"Select table1.id, table1.txt, (select table2.nr from table2 wheretable2.fk_table1=table1.id) as nr where table1.id<>10"The essence here is that "select table2.nr from table2 wheretable2.fk_table1=table1.id" returns either the integer in table2.nr, or NULLif there isnt a match. The whole sentence runs EXTREMELY slow...3-4 sec.What is wrong?"select table2.nr from table2 where table2.fk_table1=table1.id" runs quicklyoutside the stored procedure. The original sentence without the "nr" (Selecttable1.id, table1.txt where table1.id<>10) runs quickly too...But together it slows down dramatically..why? I should mention that thesub-query could return NULL if theres no match in table2...But i cant seewhy that should slow things down (remember - it runs fine outside the SP)?Thx,PipHans---Outgoing mail is certified Virus Free.Checked by AVG anti-virus system (http://www.grisoft.com).Version: 6.0.518 / Virus Database: 316 - Release Date: 11-09-2003

View 3 Replies View Related

Store Procedure Does Not Return All Rows Sometimes, Slow Execution...!!!

Oct 14, 2007

Dear friends,I have a problem with a simple select statement and I don't know why it is happening.I have 2 tables, Fees and FeesDataRoles. Fees presents all the fees and FeesDataRole is a middle table between Fees and Roles table. So each fee can have multiple Roles and a Role can have many Fees.Now I have a select statement:Select    *From     Fees Inner Join FeesDataRoles ON Fees.FeeID = FeesDataRoles.FeeIDWhere  (FeesDataRoles.DataRoleID = @DataRoleID) AND (FeesDataRoles.RecordStatus = 1 ) AND (FeesDataRoles.ValidFrom >= getdate() ) AND ( FeesDataRoles.ValidTo <= getdate() OR FeesDataRoles.ValidTo is null)Now it shouldn't take that long to execute this procedure but surprisingly sometimes when I insert a value to the table and then execute this store procedure it does now show the data just added. Very strange.....!!!!I ran the procedure 5 times after inserting an item and nearly 1 out of 5 does not return the right result righ. ( It does not include the recently inserted rows)Anyone have any idea....?I used Tuning Advisor, no sugestion. I change the clustered index in FeesDataRoles from FeesDataRoleID(the primary key of the table) to DataRoleID to increase the performance, still it happens sometimes.Is my Where clause so costly that cause this problem.Please help. I really appreciate your help.Regards,Mehdi 

View 2 Replies View Related

Visual Basic Slow Down Sql Server 2000 Running A Stored Procedure

Nov 30, 2007

I hav the following problem. I have written an stored procedure in sql server 2000 as the following
CREATE PROCEDURE dbo.pa_rellena
@pFechaInicio datetime

AS
declare @pFechaFin datetime
declare @auxcod_cen char(10)

declare @importeEfectivo decimal(17,2)
declare @importeTarjetas1 decimal(17,2)
declare @importeTarjetas2 decimal(17,2)
declare @importeVales decimal(17,2)
declare @importeTalones decimal(17,2)
declare @importeGastos decimal(17,2)


select @pFechaFin=@pFechaInicio+1


--Borramos las tablas temporales si las hemos creado con anterioridad y no se han borrado
if object_id('tmpCentros') is not null
drop table tmpCentros

if object_id('tmpCentros2') is not null
drop table tmpCentros2

if object_id('tmpMaxCajas') is not null
drop table tmpMaxCajas

if object_id('tmpCajasCentro') is not null
drop table tmpCajasCentro

if object_id('tmpVales') is not null
drop table tmpVales

if object_id('tmpDiarioEfectivo') is not null
drop table tmpDiarioEfectivo

if object_id('tmpDiarioTalones') is not null
drop table tmpDiarioTalones

if object_id('tmpDiarioTarjetas') is not null
drop table tmpDiarioTarjetas

if object_id('tmpDiarioSegundaForma') is not null
drop table tmpDiarioSegundaForma

if object_id('tmpDiarioGastosTarjetas') is not null
drop table tmpDiarioGastosTarjetas

if object_id('temp1') is not null
drop table temp1

--Seleccionamos todos los centros de Salvador Bachiller
select * into tmpCentros2
from centros
where centros.tienda=1
order by cod_cen

--Seleccionamos el maximo de cajas por cada centro

select cod_cen, max(cod_caja) as cajas into tmpMaxCajas
from cierrecaja
where fecha>=@pFechaInicio and fecha<@pFechaFin
group by cod_cen
order by cod_cen

--Mezclamos los centros con el maximo de cajas
select c.cod_cen, c.Centro, c.Direccion, c.localidad, c.provincia, c.cpostal, c.telefono, m.cajas, operaciones, cajas_tot, tienda, franquicia into tmpCentros
from tmpCentros2 as c left outer join tmpMaxCajas as m on c.cod_cen=m.cod_cen

--Cajas por centro
select distinct cod_cen as cod_cen, cod_caja as cod_caja into tmpCajasCentro
from cierrecaja
where fecha>=@pFechaInicio and fecha<@pFechaFin

--Los vales de cada centro
select cod_cen,sum(importe) as imp1 into tmpVales
from vales where
fecha>=@pFechaInicio and fecha<@pFechaFin
group by cod_cen

--Efectivo de cada centro
select cod_cen,'01' as vendedor,'EFECTIVO' as descripcion, (sum(diario.TotEuro)-Sum(Diario.Imppa2)) as importe1,0 as exp1, (sum(Diario.TotEuro)-sum(Diario.imppa2)) as importe2 into tmpDiarioEfectivo
from diario
where fecha>=@pFechaInicio and fecha<@pFechaFin and cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and diario.cod_pago='01'
group by cod_cen

--Talones por centro
select centros.cod_cen,'02' as vendedor,'TALONES' as descripcion, sum(diario.TotEuro) as importe1,0 as exp1, sum(Diario.TotEuro) as importe2 into tmpDiarioTalones
from centros inner join diario on centros.cod_cen=diario.cod_cen
where fecha>=@pFechaInicio and fecha<@pFechaFin and diario.cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and diario.cod_pago='02'
group by centros.cod_cen

--Tarjetas por centro
select cod_cen,'03' as vendedor,'TARJETAS' as descripcion, sum(diario.TotEuro) as importe1,0 as exp1, sum(Diario.TotEuro*(FPago.Descuento/100)) as importe2, sum(Diario.TotEuro) - sum(Diario.TotEuro*(FPago.Descuento/100)) as importe3 into tmpDiarioTarjetas
from FPago left join Diario on fpago.Cod_pago=Diario.cod_pago
where fecha>=@pFechaInicio and fecha<@pFechaFin and cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and Fpago.Descuento<>0
group by cod_cen

--Segunda Froma de Pago
select cod_cen,'03' as vendedor,'TARJETAS' as descripcion,sum(diario.imppa2) as importe1 into tmpDiarioSegundaForma
from fpago left join Diario on Fpago.cod_pago=diario.cod_pa1
where fPago.cod_pago<>'99' and fecha>=@pfechaInicio and fecha<@pFechaFin and cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and Fpago.Descuento<>0
group by cod_cen

--Comisiones tarjetas de pago
select cod_cen,'10' as vendedor, 'GASTOS (-)' as descripcion, sum(Diario.imppa2*(fPago.Descuento/100)) as importe2 into tmpDiarioGastosTarjetas
from Fpago left join Diario on FPago.cod_pago= Diario.cod_pa1
where fPago.cod_pago<>'99' and fecha>=@pFechaInicio and fecha<@pFechaFin and cod_cen in (select cod_cen from tmpCentros) and cod_caja in (select cod_caja from tmpCajasCentro) and Fpago.Descuento<>0
group by cod_cen
/*
--Venta neta por centro
declare cursortemporal cursor for select cod_cen from TmpCentros2

open cursortemporal
delete detallecaja_aux
fetch next from cursortemporal into @auxcod_cen
while @@fetch_status=0
Begin
select @importeVales=imp1 from tmpVales where cod_cen=@auxcod_Cen
select @importeEfectivo=importe2 from tmpDiarioEfectivo where cod_cen=@auxcod_Cen
select @importeTalones=importe2 from tmpDiarioTalones where cod_cen=@auxcod_cen
select @importeTarjetas1=importe3 from tmpDiarioTarjetas where cod_cen=@auxcod_cen
select @importeTarjetas2=importe1 from tmpDiarioSegundaForma where cod_cen=@auxcod_cen
select @importeGastos=importe2 from tmpDiarioGastosTarjetas where cod_cen=@auxcod_cen

select @importeVales=isnull(@importeVales,0)
select @importeEfectivo=isnull(@importeEfectivo,0)
select @importeTalones=isnull(@importeTalones,0)
select @importeTarjetas1=isnull(@importeTarjetas1,0)
select @importeTarjetas2=isnull(@importeTarjetas2,0)
select @importeGastos=isnull(@importeGastos,0)

print @auxcod_cen
print @importeVales
print @importeEfectivo
print @importeTalones
print @importeTarjetas1
print @importeTarjetas2
print @importeGastos

insert into detallecaja_aux (cod_cen,importe1)
values(@auxcod_cen, @importeVales+@importeEfectivo+@ImporteTalones+@ImporteTarjetas1+@importeTarjetas2-@importeGastos)
fetch next from cursortemporal into @auxcod_cen

select @importeVales=0
select @importeEfectivo=0
select @importeTalones=0
select @importeTarjetas1=0
select @importeTarjetas2=0
select @importeGastos=0
end

close cursortemporal
*/
select * from detallecaja_aux
GO

When I try to run it from visual basic it slow down the sql server.

What can I do?

View 2 Replies View Related

Should I Use A View Or A Stored Procedure

Apr 5, 2007

I'm modifying a pretty big web application and the programmer who built it used all stored procedures and no views.  Does anyone know why someone would do this?  I realize that you can't pass parameters with views and insert/update/delete records with views, but he even used stored procedures for queries like: SELECT * FROM myTable WHERE myVal > 0 ORDER BY myVal Is it more efficient to put this in a stored procedure compared a view?  

View 1 Replies View Related

View Vs. Stored Procedure

Jul 7, 2000

Are there performace benefits to using a select from a View instead of a stored procedure that returns the same dataset? I am concerned about when we ramp up to 100's of users.

View 3 Replies View Related

Stored Procedure Vs View

Jan 23, 2006

I like the security of using stored procedures. It seems I am able to do anything with it that I can with a view. Why would I choose a view over a sproc?

View 3 Replies View Related

Having Store Procedure Instead Of View

Mar 17, 2015

I have the following code to create a view. Instead of having a view I would like to convert this code to create a store procedure so the data is saved in a table.

SELECT TOP (100) PERCENT StockCode, MAX(categ) AS categ, MAX(flavor) AS flavor, MAX(Type) AS Type
FROM (SELECT RTRIM(KeyField) AS StockCode, RTRIM(AlphaValue) AS categ, RTRIM(AlphaValue) AS flavor, RTRIM(AlphaValue) AS Type, DateValue
FROM companyB.dbo.AdmFormData WHERE (0 = 1)
UNION ALL

[Code] ....

View 2 Replies View Related

Stored Procedure Or View?

Mar 14, 2007

Hello all I am not quite a beginner but not an expert at SQL. I'm kind of in a bind and need some help. I have a table that shows me statuses of tickets (open, pending, closed), some tickets could have as much as 25 rows/ticket. I want to try to avoid that but at the same time keep track of the time. Here's what I need to happen...

with the data example below I need to take the ((closed date - first open date) - total of Waiting time). This will give me total time duration of the ticket. I'd like to either write a stored procedure or create a view that would do this for me. Any one have ideas?

CallID DateStopTimeStopCallStatus
002161772006-01-2005:39:24Open
002161772006-01-2005:39:27Open
002161772006-01-2005:40:13Open
002161772006-01-2005:40:24Pending
002161772006-02-0716:05:47Pending
002161772006-02-2117:26:22Pending
002161772006-02-2117:29:06Pending
002161772006-02-2117:29:08Open
002161772006-03-0316:35:10Open
002161772006-04-0515:12:26Open
002161772006-04-0515:17:09Open
002161772006-04-1414:37:49Open
002161772006-04-1414:37:54Awaiting
002161772006-04-1911:20:30Awaiting
002161772006-04-1912:12:34Awaiting
002161772006-04-1912:12:37Awaiting
002161772006-04-1912:12:58Awaiting
002161772006-04-1912:13:00Closed[/b]

View 20 Replies View Related

Stored Procedure From The View

Sep 25, 2007

How can I create a stored procedure that combines the results from three views, and puts them in a temp table?

View 20 Replies View Related

Using A Stored Procedure In A View

Jan 1, 2008

Hi all,
I want to know if there is a way to use a stored procedure in a view OR
a table value function OR
use the store procedure in table value function.

If any of these is a possibility, it would help. So far i have learnt that extended stored procedures can be accessed in table value functions.

Thanks.

View 1 Replies View Related

Using A Stored Procedure In A View

Jan 1, 2008

Hi all,
I want to know if there is a way to use a stored procedure in a view OR
a table value function OR
use the store procedure in table value function.

If any of these is a possibility, it would help. So far i have learnt that extended stored procedures can be accessed in table value functions.

Thanks.

View 1 Replies View Related

Help Coverting A Stored Procedure To A View

Aug 13, 2007

Can someone help me convert this stored procedure to a view? It is using two UDFs.
I appreciate this very much!@Start datetime,
@End datetime

AS

SELECT

C.Client_ID, (SUM(COALESCE(PR.AmountPaid,0))+ SUM(COALESCE(SC.SC_AMOUNT,0))) AS SumOfpmts, C.OrgName, C.FirstName, C.LastName, C.Sal1, C.Sal2, C.Sal3, A.Address, A.Address_Line2, A.City, A.State, A.Zip, A.Country, C.Title,
dbo

.getLevel(SUM(COALESCE(PR.AmountPaid,0))+ SUM(COALESCE(SC.SC_AMOUNT,0))) as pmtLevel,
dbo

.getLevelDesc(SUM(COALESCE(PR.AmountPaid,0))+ SUM(COALESCE(SC.SC_AMOUNT,0))) as Description
FROM

tblClients C INNER JOIN
tblPMTs P

ON C.Client_ID = P.Client_ID INNER JOIN
tblPMTReceipts PR

ON P.PMT_ID = PR.PMT_ID INNER JOIN
tblClientAddresses A

ON C.Client_ID = A.Client_ID LEFT OUTER JOIN
tblSoftCreditsPMTS SC

ON C.Client_ID = SC.SC_Client_ID

WHERE

(PR.PaymentDate BETWEEN @Start AND @End)
GROUP

BY C.Client_ID, C.OrgName, C.FirstName, C.LastName, C.Sal1, C.Sal2, C.Sal3, A.Address, A.Address_Line2, A.City, A.State, A.Zip, A.Country, C.Title

ORDER

BY pmtLevel
RETURN 

View 3 Replies View Related

Using Stored Procedure In View As A Table ?!

Aug 28, 2007

Hi guys
I have a stored procedure that a make crosstab table , In this table the main column is "job titles" these jobs  must be ordered  in certain  way , for example "1st managers then engineers  … workers  … " so In the table that   job titles are defined  there is also a column named "Ranking" so the" job titles" could be sorted appropriately by ranking order .
The problem is I cannot have the "Ranking" column with my crosstab table so I need to load it in a view or something like that.
Any Idea?
 

View 8 Replies View Related

Updating A View Through A Stored Procedure.

Oct 14, 2007

Hi i have a page in which a user fills out info on a page, the problem i am getting is that when the save button is clicked all text box values apart from one are saving to the database this field is the "constructor_ID" field. The save button performs a stored procedure, however there is a view which is doing something as well, would it be possible to write a stored procedure which would update the view at the same time?
CREATE PROCEDURE sp_SurveyMainDetails_Update
@Constructor_ID  int,@SurveyorName_ID int,@Survey_Date char(10),@Survey_Time char (10),@AbortiveCall bit,@Notes  text,@Survey_ID int,@User_ID int,@Tstamp timestamp out AS
 
DECLARE @CHANGED_Tstamp timestampDECLARE @ActionDone char(6)SET @ActionDone = 'Insert'
SET @CHANGED_Tstamp = (SELECT Tstamp FROM tblSurvey WHERE Survey_ID = @Survey_ID)IF @Tstamp <> @CHANGED_Tstamp --AND @@ROWCOUNT =0 BEGIN  SET @Tstamp =  @CHANGED_Tstamp  RAISERROR('This survey has already been updated since you opened this record',16,1)  RETURN 14 ENDELSE
   BEGIN
SELECT * FROM tblSurvey WHERE  Constructor_ID   = @Constructor_ID   AND  --Contractor_ID  = @Contractor_ID  AND  Survey_DateTime = Convert(DateTime,@Survey_Date + ' ' + LTRIM(RTRIM(@Survey_Time)), 103) AND  IsAbortiveCall = @AbortiveCall     IF @@ROWCOUNT>0                          SET @ActionDone = 'Update'
UPDATE tblSurvey SET    Constructor_ID   = @Constructor_ID   ,  SurveyorName_ID   = @SurveyorName_ID ,     Survey_DateTime = Convert(DateTime,@Survey_Date + ' ' + LTRIM(RTRIM(@Survey_Time)), 103) ,  IsAbortiveCall = @AbortiveCall ,  Note  = @Notes               WHERE Survey_ID = @Survey_ID AND Tstamp = @Tstamp IF @@error = 0 begin                        exec dhoc_ChangeLog_Insert    'tblSurvey',  @Survey_ID,  @User_ID,  @ActionDone,  'Main Details',  @Survey_ID
    end else BEGIN  RAISERROR ('The request has not been proessed, it might have been modifieid since you last opened it, please try again',16,1)  RETURN 10   END SELECT * FROM tblSurvey WHERE Survey_ID=@Survey_ID     
END
--Make sure this has saved, if not return 10 as this is unexpected error
--SELECT * FROM tblSurvey
DECLARE @RETURN_VALUE tinyintIF @@error <>0 RETURN @@errorGO
 This is the view;
CREATE VIEW dbo.vw_Property_FetchASSELECT     dbo.tblPropertyPeriod.Property_Period, dbo.tblPropertyType.Property_Type, dbo.tblPropertyYear.Property_Year, dbo.tblProperty.Add1,                       dbo.tblProperty.Add2, dbo.tblProperty.Add3, dbo.tblProperty.Town, dbo.tblProperty.PostCode, dbo.tblProperty.Block_Code, dbo.tblProperty.Estate_Code,                       dbo.tblProperty.UPRN, dbo.tblProperty.Tstamp, dbo.tblProperty.Property_ID, dbo.tblProperty.PropertyStatus_ID, dbo.tblProperty.PropertyType_ID,                       dbo.tblProperty.Correspondence_Add4, dbo.tblProperty.Correspondence_Add3, dbo.tblProperty.Correspondence_Add2,                       dbo.tblProperty.Correspondence_Add1, dbo.tblProperty.Correspondence_Phone, dbo.tblProperty.Correspondence_Name,                       dbo.tblPropertyStatus.Property_Status, dbo.tblProperty.Floor_Num, dbo.tblProperty.Num_Beds, dbo.vw_LastSurveyDate.Last_Survey_Date,                       dbo.tblProperty_Year_Period.Constructor_ID, dbo.tblProperty_Year_Period.PropertyPeriod_ID, dbo.tblProperty_Year_Period.PropertyYear_ID,                       LTRIM(RTRIM(ISNULL(dbo.tblProperty.Add1, ''))) + ', ' + LTRIM(RTRIM(ISNULL(dbo.tblProperty.Add2, '')))                       + ', ' + LTRIM(RTRIM(ISNULL(dbo.tblProperty.Add3, ''))) + ', ' + LTRIM(RTRIM(ISNULL(dbo.tblProperty.PostCode, ''))) AS Address,                       dbo.tblProperty.TenureFROM         dbo.tblPropertyType RIGHT OUTER JOIN                      dbo.tblProperty LEFT OUTER JOIN                      dbo.tblProperty_Year_Period ON dbo.tblProperty.Property_ID = dbo.tblProperty_Year_Period.Property_ID LEFT OUTER JOIN                      dbo.vw_LastSurveyDate ON dbo.tblProperty.Property_ID = dbo.vw_LastSurveyDate.Property_ID LEFT OUTER JOIN                      dbo.tblPropertyStatus ON dbo.tblProperty.Status_ID = dbo.tblPropertyStatus.PropertyStatus_ID ON                       dbo.tblPropertyType.PropertyType_ID = dbo.tblProperty.PropertyType_ID LEFT OUTER JOIN                      dbo.tblPropertyPeriod ON dbo.tblProperty.PropertyPeriod_ID = dbo.tblPropertyPeriod.PropertyPeriod_ID LEFT OUTER JOIN                      dbo.tblPropertyYear ON dbo.tblProperty.PropertyYear_ID = dbo.tblPropertyYear.PropertyYear_ID
   
 

View 1 Replies View Related

Is It Possible To Create A View From A Stored Procedure

Jan 3, 2008

Is it possible to drop and then create a view from a stored procedure? Like the way you can drop and create a temp table.
I want to create a view of the fields in a table something like: But I cannot include the field names, they may be changed by an admin user.
If exists view 'custom_fields"
drop view 'custom_fields'
Create view custom_fields
Select * From tblCustomFields
And make this a view in the db named custom_fields.
And I want to call it from a button click in my UI.

View 9 Replies View Related

When To Use ? Stored Procedure V/s View In SQL Server

Dec 6, 2005

hi,
Can someone tell me when to use SQL Server View as oppose to Stored Porcedure?
Currently we do everything with SQL Server stored procedure. I mean, even if we have to display some report, we use Stored Procedure.
In what situations and senarios views are better and one should consider them over Stored Procedure?

View 13 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved