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 where
table2.fk_table1=table1.id) as nr where table1.id<>10"

The essence here is that "select table2.nr from table2 where
table2.fk_table1=table1.id" returns either the integer in table2.nr, or NULL
if 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 quickly
outside the stored procedure. The original sentence without the "nr" (Select
table1.id, table1.txt where table1.id<>10) runs quickly too...

But together it slows down dramatically..why? I should mention that the
sub-query could return NULL if theres no match in table2...But i cant see
why 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


ADVERTISEMENT

Sql Stored Procedure Question - Easy

Apr 23, 2005

Hi Everyone,
I ran into something interesting this afternoon as i was trying to create a stored procedure. 
<code>
Create Procedure GrabRecentPresentations
As
Select * from tablePresentations Order By PresentationID DESC
Go
</code>Works fine.. but if i try to do this
Create Procedure GrabRecentPresentations
As(
Select * from tablePresentations Order By PresentationID DESC
)
Go
 
I get an error: incorrect syntax near the keyword 'Order'
It seems that by adding those two ( ) i get the error... does anyone know why this happens or a way to make it so that i can keep those beloved parentheses?  Furthermore.. why does the error only pop up when i have those in?  THanks

View 5 Replies View Related

How To FAST And EASY ENCRYPTION ALL Stored Procedure In My MS-SQL Database ?

Jun 16, 2006

My MS-SQL 2000 Database have 50 more Stored Procedure .How to FAST and EASY ENCRYPTION ALL Stored Procedure in my MS-SQLDatabase?

View 1 Replies View Related

Any Easy Class Method To Update About 100 Fields Of A Database Using Stored Procedure?

Feb 1, 2007

Hi all,
 I am using  C# for ASP.NEt 2003.
I would like to know if there is any easy method to update a database with about 100 fields in it.
At present, I pass all the values of the controls on the web form to the stored procedure as parameters like :-
myCommand.Parameters.Add("@CustomerID", SqlDbType.Int).Value = txtCustomerID.text
Like this,  I add all 100 parameters.
Is there any easy method to do it using a class or any other methods?
Thanking you in advance,
Tomy

View 2 Replies View Related

How To Run A Stored Procedure Located In One Database Against Another Database

Feb 14, 2008



I have a stored procedure that is located in one database and I would like to have it execute against a different database. My problem is when I go to execute it, it is still executing against the database it is stored in. Is it possible to tell this stored procedure when it runs to execute its code against this second database?

This is what I have now, which isn't working:




Code Snippet

use [Database2]
exec [Database1].[dbo].usp_SetupDatabaseUser





The end result still executes against Database1.

Thanks for any advice,

Flea#

View 9 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

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

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

Procedure For Modifying A Field In The Row Located Two Positions Before The Last One

Sep 15, 2006

I want to create a procedure where each time I add a new record to a table I want to set the field “Display” ( BIT ) to “false” in a position that is two rows before the last one. How to do that ?

View 2 Replies View Related

SQL Server 2005 Stored Procedure Is Very Slow Vs. SQL Server 2000

Apr 18, 2008

Hi there,

I was wondering if someone can point out the error or the thing I shouldn't be doing in a stored procedure on SQL Server 2005. I want to switch from SQL Server 2000 to SQL Server 2005 which all seems to work just fine, but one stored procedure is causing me headache.

I could pin the problem down to this query:


DECLARE @Package_ID bigint

DECLARE @Email varchar(80)

DECLARE @Customer_ID bigint

DECLARE @Payment_Type tinyint

DECLARE @Payment_Status tinyint

DECLARE @Booking_Type tinyint

SELECT @Package_ID = NULL

SELECT @Email = NULL

SELECT @Customer_ID = NULL

SELECT @Payment_Type = NULL

SELECT @Payment_Status = NULL

SELECT @Booking_Type = NULL

CREATE TABLE #TempTable(

PACKAGE_ID bigint,

PRIMARY KEY (PACKAGE_ID))

INSERT INTO

#TempTable

SELECT

PACKAGE.PACKAGE_ID

FROM

PACKAGE (nolock) LEFT JOIN BOOKING ON PACKAGE.PACKAGE_ID = BOOKING.PACKAGE_ID

LEFT JOIN CUSTOMER (nolock) ON PACKAGE.CUSTOMER_ID = CUSTOMER.CUSTOMER_ID

LEFT JOIN ADDRESS_LINK (nolock) ON ADDRESS_LINK.SOURCE_TYPE = 1 AND ADDRESS_LINK.SOURCE_ID = CUSTOMER.CUSTOMER_ID

LEFT JOIN ADDRESS (nolock) ON ADDRESS_LINK.ADDRESS_ID = ADDRESS.ADDRESS_ID

WHERE

PACKAGE.PACKAGE_ID = ISNULL(@Package_ID,PACKAGE.PACKAGE_ID)

AND PACKAGE.CUSTOMER_ID = ISNULL(@Customer_ID,PACKAGE.CUSTOMER_ID)

AND PACKAGE.PAYMENT_TYPE = ISNULL(@Payment_Type,PACKAGE.PAYMENT_TYPE)

AND PACKAGE.PAYMENT_STATUS = ISNULL(@Payment_Status,PACKAGE.PAYMENT_STATUS)

AND BOOKING.BOOKING_TYPE = ISNULL(@Booking_Type,BOOKING.BOOKING_TYPE)

-- If this line below is included the request will take about 90 seconds whereas it takes 1 second if it is outcommented

--AND ADDRESS.EMAIl LIKE '%' + ISNULL(@Email, ADDRESS.EMAIL) + '%'

GROUP BY

PACKAGE.PACKAGE_ID

DROP TABLE #TempTable


The request is performing quite well on the SQL Server 2000 but on the SQL Server 2005 it takes much longer. I already installed the SP2 x64, I'm running the SQL Server 2005 on a x64 environment.
As I stated in the comment in the query it takes 90 seconds to finish with the line included, but if I exclude the line it takes 1 second.
I think there must be something wrong with the join's or something else which has maybe changed in SQL Server 2005. All the tables joined have a primary key.
Maybe you folks can spot the error / mistake / wrong type of doing things easily.
I would appreciate any help you can offer me to solve this problem.

On the web I saw that there is a Cumulative Update 4 for the SP2 which fixes the following:





942659 (http://support.microsoft.com/kb/942659/)
FIX: The query performance is slower when you run the query in SQL Server 2005 than when you run the query in SQL Server 2000

Anyhow I think the problem is something else, I haven't tried out the cumulative update yet, as I think it is something different, more general why this query takes ages to process.

Thanks again for any help

Best regards,
Pascal

View 9 Replies View Related

Really Easy Stored Proc Question

Jan 20, 2004

I suppose it's not possible to return a varchar value from a stored proc? I keep getting a conversion error.

How can I return a varchar value, then?

Thanks.. sorry for the stupid question. I did some searching on Google and didn't find much.

View 4 Replies View Related

Is There An Easy Way To Delete Stored Procedures?

Mar 21, 2007

Hi All,

In SQL server 2000 enterprise manager you were able to select multiple stored procedures and drop them all in one go. In 2005 all the stored procs are listed differently (in a tree view) and you cannot therefore select multiple SP for deleteing. Is there another way to accomplish this?

Danny

View 3 Replies View Related

Image Located On Web, Url For Image Stored In Database

Aug 17, 2007



Hi,
I have a website and i am uploading the gif image to the database. i have used varchar(500) as the datatype and i am saving the file in the webserver so the path to it c:intepub....a.gif


my upload table has the folliwing feilds
UploadId Int Identity, Description, FileName, DiskPath varchar(500), weblocation varchar(500). I have a main sproc for the report where i am doing a inner join with other table to get the path of the gif..

So my question is how can i get a picture to show up on the report. .
What kinda datatype the gif file should be stored in the database? If it is stored as a varchar how can i access it and what is best way to reference that particular.

any help will appreciated....
Regards
Karen

View 9 Replies View Related

Easy Question, How Do I Put A Paramater In Stored Proc, With A Memory Table

Apr 11, 2008

All i want to do is add a parameter for Territory_code how do i do that, in a stored procedure that uses a memory table.
the yellow shows the two places i thought i should be able to include it. Any help will be greatly appreciated!! thanks!
I couldnt post the whole code, so i deleted alot , just need to know where to put the param!




Code Snippet

USE [RC_STAT]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER PROCEDURE [dbo].[PROC_RPT_Breeder_Sales]
AS (@Territory varchar(20)
BEGIN
SET NOCOUNT ON;

Declare @ReportingTbl TABLE (
Source_Id int,
Territory_Code varchar(20),
Territory_Description varchar (30),
Sort_Id int,
Column_Text varchar(20),
Subbrand_Key int,
SubBrand_Description varchar (30),
Period_1 Decimal(18,0),
Period_2 Decimal(18,0),
Period_3 Decimal(18,0),
Period_4 Decimal(18,0),
Period_5 Decimal(18,0),
Period_6 Decimal(18,0),
Period_7 Decimal(18,0),
Period_8 Decimal(18,0),
Period_9 Decimal(18,0),
Period_10 Decimal(18,0),
Period_11 Decimal(18,0),
Period_12 Decimal(18,0),
Period_13 Decimal(18,0),
YTD Decimal (18,0),
Total_Amount decimal (18,0))
------------------------------------------------------------------------------------------------------------------------------------------
----Distributor Load Section
------------------------------------------------------------------------------------------------------------------------------------------
INSERT INTO @ReportingTbl
(Source_Id,
Territory_Code,
Territory_Description,
Sort_Id,
Column_Text,
Subbrand_Key,
SubBrand_Description,
Period_1,
Period_2,
Period_3,
Period_4,
Period_5,
Period_6,
Period_7,
Period_8,
Period_9,
Period_10,
Period_11,
Period_12,
Period_13,
YTD,
Total_Amount)
SELECT
1 as Source_Id,
Tbv_Customer.Breeder_Territory_Code,
RC_DWDB_INSTANCE_1.dbo.Qry_Sales_Group_Dimension.Territory_Name,
CASE WHEN cusSales.Customer_Sales_Summary_Year = YEAR(GETDATE()) THEN 2 ELSE 1 END as Sort_Id,
cusSales.Customer_Sales_Summary_Year Column_Text,
cusSales.Sub_Brand_Id ,
Qry_Report_Level_Brand.Sub_Brand_Description,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 1 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END)AS Period_1,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 2 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_2,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 3 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_3,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 4 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_4,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 5 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_5,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 6 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_6,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 7 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_7,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 8 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_8,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 9 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_9,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 10 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END)AS Period_10,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 11 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_11,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 12 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_12,
SUM(CASE cusSales.Customer_Sales_Summary_Period WHEN 13 THEN cusSales.Customer_Sales_Summary_Amount ELSE 0 END) AS Period_13,
0 as YTD,
SUM (cusSales.Customer_Sales_Summary_Amount) As Total
FROM RC_DWDB_INSTANCE_1.dbo.Qry_Sales_Group_Dimension
INNER JOIN Tbv_Customer ON RC_DWDB_INSTANCE_1.dbo.Qry_Sales_Group_Dimension.Territory_Code = Tbv_Customer.Breeder_Territory_Code
INNER JOIN RC_DWDB_INSTANCE_1.dbo.Tbl_Customer_Sales_Summary_Fiscal AS cusSales
ON Tbv_Customer.Customer_Code = cusSales.Customer_Code
INNER JOIN Qry_Report_Level_Brand
ON cusSales.Sub_Brand_Id = Qry_Report_Level_Brand.Sub_Brand_Id
WHERE
cusSales.Bill_Customer_Code NOT IN ('RNPROC','RNPROF')
AND cusSales.Sub_Brand_Id <> 65 AND cusSales.Report_Level_Id = 85
AND cusSales.Report_Level_Id = 85
AND cusSales.Consolidated_Sales_Tables_Id = 6
AND cusSales.Customer_Sales_Summary_Year >= YEAR(GETDATE()) - 1
GROUP BY
Tbv_Customer.Breeder_Territory_Code,
RC_DWDB_INSTANCE_1.dbo.Qry_Sales_Group_Dimension.Territory_Name,
cusSales.Customer_Sales_Summary_Year,
cusSales.Sub_Brand_Id ,
Qry_Report_Level_Brand.Sub_Brand_Description


SELECT
Source_Id,
Territory_Code,
Territory_Description,
Sort_Id,
Column_Text,
Subbrand_Key,
SubBrand_Description,
Period_1,
Period_2,
Period_3,
Period_4,
Period_5,
Period_6,
Period_7,
Period_8,
Period_9,
Period_10,
Period_11,
Period_12,
Period_13,
YTD,
Total_Amount
FROM @ReportingTbl
-- ORDER BY Source_Id, Sort_Id
where Territory_Code=@Territory
END





View 6 Replies View Related

Calling A Stored Procedure Inside Another Stored Procedure (or Nested Stored Procedures)

Nov 1, 2007

Hi all - I'm trying to optimized my stored procedures to be a bit easier to maintain, and am sure this is possible, not am very unclear on the syntax to doing this correctly.  For example, I have a simple stored procedure that takes a string as a parameter, and returns its resolved index that corresponds to a record in my database. ie
exec dbo.DeriveStatusID 'Created'
returns an int value as 1
(performed by "SELECT statusID FROM statusList WHERE statusName= 'Created') 
but I also have a second stored procedure that needs to make reference to this procedure first, in order to resolve an id - ie:
exec dbo.AddProduct_Insert 'widget1'
which currently performs:SET @statusID = (SELECT statusID FROM statusList WHERE statusName='Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
I want to simply the insert to perform (in one sproc):
SET @statusID = EXEC deriveStatusID ('Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
This works fine if I call this stored procedure in code first, then pass it to the second stored procedure, but NOT if it is reference in the second stored procedure directly (I end up with an empty value for @statusID in this example).
My actual "Insert" stored procedures are far more complicated, but I am working towards lightening the business logic in my application ( it shouldn't have to pre-vet the data prior to executing a valid insert). 
Hopefully this makes some sense - it doesn't seem right to me that this is impossible, and am fairly sure I'm just missing some simple syntax - can anyone assist?
 

View 1 Replies View Related

Calling A Stored Procedure From ADO.NET 2.0-VB 2005 Express: Working With SELECT Statements In The Stored Procedure-4 Errors?

Mar 3, 2008

Hi all,

I have 2 sets of sql code in my SQL Server Management Stidio Express (SSMSE):

(1) /////--spTopSixAnalytes.sql--///

USE ssmsExpressDB

GO

CREATE Procedure [dbo].[spTopSixAnalytes]

AS

SET ROWCOUNT 6

SELECT Labtests.Result AS TopSixAnalytes, LabTests.Unit, LabTests.AnalyteName

FROM LabTests

ORDER BY LabTests.Result DESC

GO


(2) /////--spTopSixAnalytesEXEC.sql--//////////////


USE ssmsExpressDB

GO
EXEC spTopSixAnalytes
GO

I executed them and got the following results in SSMSE:
TopSixAnalytes Unit AnalyteName
1 222.10 ug/Kg Acetone
2 220.30 ug/Kg Acetone
3 211.90 ug/Kg Acetone
4 140.30 ug/L Acetone
5 120.70 ug/L Acetone
6 90.70 ug/L Acetone
/////////////////////////////////////////////////////////////////////////////////////////////
Now, I try to use this Stored Procedure in my ADO.NET-VB 2005 Express programming:
//////////////////--spTopSixAnalytes.vb--///////////

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim sqlConnection As SqlConnection = New SqlConnection("Data Source = .SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = ssmsExpressDB;")

Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdaptor("[spTopSixAnalytes]", sqlConnection)

sqlDataAdapter.SelectCommand.Command.Type = CommandType.StoredProcedure

'Pass the name of the DataSet through the overloaded contructor

'of the DataSet class.

Dim dataSet As DataSet ("ssmsExpressDB")

sqlConnection.Open()

sqlDataAdapter.Fill(DataSet)

sqlConnection.Close()

End Sub

End Class
///////////////////////////////////////////////////////////////////////////////////////////

I executed the above code and I got the following 4 errors:
Error #1: Type 'SqlConnection' is not defined (in Form1.vb)
Error #2: Type 'SqlDataAdapter' is not defined (in Form1.vb)
Error #3: Array bounds cannot appear in type specifiers (in Form1.vb)
Error #4: 'DataSet' is not a type and cannot be used as an expression (in Form1)

Please help and advise.

Thanks in advance,
Scott Chang

More Information for you to know:
I have the "ssmsExpressDB" database in the Database Expolorer of VB 2005 Express. But I do not know how to get the SqlConnection and the SqlDataAdapter into the Form1. I do not know how to get the Fill Method implemented properly.
I try to learn "Working with SELECT Statement in a Stored Procedure" for printing the 6 rows that are selected - they are not parameterized.




View 11 Replies View Related

Slow Procedure Using View

Jul 20, 2005

HiI have a procedure that calls a view. The view is built with some outerjoins but it performs fine.If I run in Query Analyzerselect count(*) from long_name_viewwhere name_id = 'AAA'it returns instantlyThe procedure has the same code. I juststripped down the code to narrowthe problem:create or replace procedure my_name_proc@nid VARCHAR(32)ASDECLARE@nidkey_count INTEGERselect @nidkey_count = count(*)from long_name_viewwhere name_id = @nidprint 'The count: ' + CAST(@nidkey_count as varchar)GOWhen I call in Query Analyzer:exec my_name_proc 'AAA'it takes a while to run, over 20 sec and the execution plan isdifferent. What is the reason that the same view is used in differentways?Thanks*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 1 Replies View Related

T-SQL (SS2K8) :: One Stored Procedure Return Data (select Statement) Into Another Stored Procedure

Nov 14, 2014

I am new to work on Sql server,

I have One Stored procedure Sp_Process1, it's returns no of columns dynamically.

Now the Question is i wanted to get the "Sp_Process1" procedure return data into Temporary table in another procedure or some thing.

View 1 Replies View Related

SQL Server 2014 :: Embed Parameter In Name Of Stored Procedure Called From Within Another Stored Procedure?

Jan 29, 2015

I have some code that I need to run every quarter. I have many that are similar to this one so I wanted to input two parameters rather than searching and replacing the values. I have another stored procedure that's executed from this one that I will also parameter-ize. The problem I'm having is in embedding a parameter in the name of the called procedure (exec statement at the end of the code). I tried it as I'm showing and it errored. I tried googling but I couldn't find anything related to this. Maybe I just don't have the right keywords. what is the syntax?

CREATE PROCEDURE [dbo].[runDMQ3_2014LDLComplete]
@QQ_YYYY char(7),
@YYYYQQ char(8)
AS
begin
SET NOCOUNT ON;
select [provider group],provider, NPI, [01-Total Patients with DM], [02-Total DM Patients with LDL],

[Code] ....

View 9 Replies View Related

Connect To Oracle Stored Procedure From SQL Server Stored Procedure...and Vice Versa.

Sep 19, 2006

I have a requirement to execute an Oracle procedure from within an SQL Server procedure and vice versa.

How do I do that? Articles, code samples, etc???

View 1 Replies View Related

Grab IDENTITY From Called Stored Procedure For Use In Second Stored Procedure In ASP.NET Page

Dec 28, 2005

I have a sub that passes values from my form to my stored procedure.  The stored procedure passes back an @@IDENTITY but I'm not sure how to grab that in my asp page and then pass that to my next called procedure from my aspx page.  Here's where I'm stuck:    Public Sub InsertOrder()        Conn.Open()        cmd = New SqlCommand("Add_NewOrder", Conn)        cmd.CommandType = CommandType.StoredProcedure        ' pass customer info to stored proc        cmd.Parameters.Add("@FirstName", txtFName.Text)        cmd.Parameters.Add("@LastName", txtLName.Text)        cmd.Parameters.Add("@AddressLine1", txtStreet.Text)        cmd.Parameters.Add("@CityID", dropdown_city.SelectedValue)        cmd.Parameters.Add("@Zip", intZip.Text)        cmd.Parameters.Add("@EmailPrefix", txtEmailPre.Text)        cmd.Parameters.Add("@EmailSuffix", txtEmailSuf.Text)        cmd.Parameters.Add("@PhoneAreaCode", txtPhoneArea.Text)        cmd.Parameters.Add("@PhonePrefix", txtPhonePre.Text)        cmd.Parameters.Add("@PhoneSuffix", txtPhoneSuf.Text)        ' pass order info to stored proc        cmd.Parameters.Add("@NumberOfPeopleID", dropdown_people.SelectedValue)        cmd.Parameters.Add("@BeanOptionID", dropdown_beans.SelectedValue)        cmd.Parameters.Add("@TortillaOptionID", dropdown_tortilla.SelectedValue)        'Session.Add("FirstName", txtFName.Text)        cmd.ExecuteNonQuery()        cmd = New SqlCommand("Add_EntreeItems", Conn)        cmd.CommandType = CommandType.StoredProcedure        cmd.Parameters.Add("@CateringOrderID", get identity from previous stored proc)   <-------------------------        Dim li As ListItem        Dim p As SqlParameter = cmd.Parameters.Add("@EntreeID", Data.SqlDbType.VarChar)        For Each li In chbxl_entrees.Items            If li.Selected Then                p.Value = li.Value                cmd.ExecuteNonQuery()            End If        Next        Conn.Close()I want to somehow grab the @CateringOrderID that was created as an end product of my first called stored procedure (Add_NewOrder)  and pass that to my second stored procedure (Add_EntreeItems)

View 9 Replies View Related

SQL Server 2012 :: Executing Dynamic Stored Procedure From A Stored Procedure?

Sep 26, 2014

I have a stored procedure and in that I will be calling a stored procedure. Now, based on the parameter value I will get stored procedure name to be executed. how to execute dynamic sp in a stored rocedure

at present it is like EXECUTE usp_print_list_full @ID, @TNumber, @ErrMsg OUTPUT

I want to do like EXECUTE @SpName @ID, @TNumber, @ErrMsg OUTPUT

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

Slow Stored Procedures

Sep 7, 2005

Hi,I have a stored procedure that normalizes data from one database toanother that is included in a SQL Agent job. The job is started by atrigger so that when a table is updated, the job to normalize dataexecutes.This happens once a day in the dead of the night when nothing else ishappening and the stored procedure takes 2.5 hours to finish. Strangely,to run the same stored procedure from Query Analyzer takes only 20minutes to do the same thing. The job is executed as the same user thatlogs in to Query Analyzer.Why does running as a job take so much longer than running it manually.At the time the job is run, there is absolutely nothing else to createwaits or deadlocks. A profiler trace shows that each statement runsquickly but then it sits and twiddles its thumbs between statements.Performance monitor shows little disk activity and only 2% to 5%processor utilization.Any ideas?

View 1 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

Stored Proc Slow Vs. ISQL

Jul 26, 1999

Hello all.

I have a stored proc which creates a couple of temp tables, then bounces them against a production table an updates a column in the production table.

This stored proc takes about 10 minutes to run and update about 20,000 rows. If I execute each statement seperately in an ISQL window, it all runs in under 2 minutes.

Any ideas on why this is happening are GREATLY appreciated.

View 1 Replies View Related

Sp_fkeys Stored Procedue Is Very Slow

May 18, 2006

I am trying to find the tables and columns that depends on 'table1'sp_fkeys @pktable_name='table1'and this takes about eight seconds, whereas if I run it for finding alltables and columns that 'table1' depends onsp_fkeys @fktable_name='table1'this only takes a second.How can I speed up the first stored procedure execution?

View 2 Replies View Related







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