AdHoc Query Faster Than Stored Proc?

Aug 28, 2004

Yesterday i face a strange SQL Server 2000 behaviour :-(

I had a query that was wrapped inside a stored procedure, as usual.
Suddenly, the stored procedure execution time raised from 9 secs to 80.

So to understand where the problem was i cut and pasted the sp body's into a new query analyzer window an then executed it again. Speed back to 9 secs.
Tried stored procedure again, and speed again set to 80 secs.

Tried to recompile sp. Nothing. Tried to restart SQL Server. Nothing. Tried to DROP & RE-CREATE sp. Done! Speed again at 9 secs.

My collegue asked me "why?", but i had no words. :confused: Do you have any explanation?

View 5 Replies


ADVERTISEMENT

Same Statement Executes 10 Times Faster As Raw Sql In Query Analyzer Then In A Stored Proc

Aug 15, 2007



Hi,


I apologize for the long post but I am trying to give as much information as I can about the steps I've taken to troubleshoot this.


We have a stored procedure that builds a sql statement and executes it using the Execute command. When I execute the stored procedure through query analyzer it takes close to 5 seconds to execute. When I print out the exact same statement and execute it directly in query analyzer as "raw sql", it takes 0.5 seconds - meaning it takes 10 times longer for the code to execute in the stored proc. I altered the stored proc to execute the printed sql instead of building but it still takes the full 5 seconds and there were no changes in the execution plan. This makes me confident that the issue is not caused by the dynamic sql. I've used with recompile to make sure that the stored procedure caches the most recent execution plan. When I compare the execution plans, the stored proc uses a nested loop whereas the raw sql statement uses a hash join. Seeing that, I added the hash hint to the stored proc and doing so brought down the execution time down from 5 secs to 2 secs but still the raw sql statement uses a clustered index whereas the stored proc uses a non-clustered index and that makes the statement 4 times slower. This proves how efficient clustered indexes are over non-clustered ones, but it doesn't help me since, as far as I know, I can't force SQL Server to use the clustered index.


Does anyone know why sql server is generating such an inefficient execution plan for the stored proc compared to the execution plan that it generates when executing the raw sql statement? The only thing I can think of is that some stats are not updated and that somehow throws off the stored proc. But then again, shouldn't it affect the raw sql statement?


Thank you,


Michael Tzoanos

View 4 Replies View Related

Make Stored Proc Faster

Jun 17, 2004

Anyone got any alternatives to the SQL Statement below that would make it run a bit faster:

ALTER PROCEDURE sproc_ReturnAvailability

@ExtractDate DateTime,
@DateFrom DateTime,
@DateTo DateTime,
@96hrPlusFlag int,
@AppointmentsCount int OUTPUT

AS

IF @96hrPlusFlag = 0

BEGIN
SELECT @AppointmentsCount = COUNT(tbl_SurgerySlot.SurgerySlotKey)
FROM tbl_SurgerySlot
INNER JOIN tbl_SurgerySlotDescription ON (tbl_SurgerySlot.Label = tbl_SurgerySlotDescription.Label AND tbl_SurgerySlot.PracticeCode = tbl_SurgerySlotDescription.PracticeCode)
AND tbl_SurgerySlot.ExtractDate = @ExtractDate
AND tbl_SurgerySlot.StartTime BETWEEN @DateFrom AND @DateTo
AND tbl_SurgerySlotDescription.NormalBookable = 1
AND tbl_SurgerySlot.SurgerySlotKey NOT IN(
SELECT tbl_Appointment.SurgerySlotKey
FROM tbl_Appointment
WHERE tbl_Appointment.ExtractDate = @ExtractDate
AND tbl_Appointment.Deleted = 0
AND tbl_Appointment.Cancelled = 0
)
END
ELSE

BEGIN
IF @96hrPlusFlag = 1

SELECT @AppointmentsCount = COUNT(tbl_SurgerySlot.SurgerySlotKey)
FROM tbl_SurgerySlot
INNER JOIN tbl_SurgerySlotDescription ON (tbl_SurgerySlot.Label = tbl_SurgerySlotDescription.Label AND tbl_SurgerySlot.PracticeCode = tbl_SurgerySlotDescription.PracticeCode)
AND tbl_SurgerySlot.ExtractDate = @ExtractDate
AND tbl_SurgerySlot.StartTime >@DateTo
AND tbl_SurgerySlotDescription.NormalBookable = 1
AND tbl_SurgerySlot.SurgerySlotKey NOT IN(
SELECT tbl_Appointment.SurgerySlotKey
FROM tbl_Appointment
WHERE tbl_Appointment.ExtractDate = @ExtractDate
AND tbl_Appointment.Deleted = 0
AND tbl_Appointment.Cancelled = 0
)

END

Cheers...

View 1 Replies View Related

Adhoc Vs PROC

Jan 4, 2007

Hi Guru,When I ran my adhoc script below it generated only 45000 reads or 4seconds but when I wrapped it into procedure it took about two minutesor millions of reads. The parameters calling both adhoc and proc areindeed the same. I'm pretty 99.9% sure that the proc does not recompilebecause I don't mix up between DDL and DML, no temp tables or any thingto cause proc to recompile. The big difference is adhoc used index scanfor 45% but proc used bookmark lookup for 75%. Why it's so differencesince they both returned the same results?Please help...Silaphet,Below is my code,DECLARE @Modevarchar(10),@UserIDvarchar(36),@FromDatesmalldatetime,@ToDatesmalldatetime,@Insttinyint,@LocationIDsmallint,@BunitIDtinyint,@TeamIDintSET @Mode='TEAM'SET @UserID=''SET @FromDate='Dec 1 2006 12:00AM'SET @ToDate='Dec 31 2006 12:00AM'SET @Inst=28SET @LocationID=0SET @BunitID=2SET @TeamID=805--IF @Mode = 'TEAM'BEGINSELECT OffAffiliateDesc, OffLocationDesc, OfficerName, Active,TeamName, '' As BUnit,Sum(CASE WHEN StartDate BETWEEN @FromDate AND @ToDate THEN 1 ELSE 0END) As CurrYr,Sum(CASE WHEN StartDate BETWEEN @FromDate-365 AND @ToDate-365 THEN 1ELSE 0 END) As PrevYr,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 1037) AND ((OutcomeId IS NULL) OR (OutcomeID =0)) AND(DATEDIFF(dd,StartDate,@ToDate) * -1 <-30) THEN 1 ELSE 0 END) AsPastDue,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 1037) THEN 1 ELSE 0 END) As Ref,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 63) THEN 1 ELSE 0 END) As CallSched,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 64) THEN 1 ELSE 0 END) As PropPres,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 65) THEN 1 ELSE 0 END) As PropAcc,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 66) THEN 1 ELSE 0 END) As BremApp,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 67) THEN 1 ELSE 0 END) As BusBook,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeId = 106) THEN 1 ELSE 0 END) As NonQual,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeId = 992) THEN 0 ELSE 0 END) As Duplicate,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeID = 107) THEN 1 ELSE 0 END) As OutdatedFROM vw_Referrals_Grouped RIGHT OUTER JOINdbo.MyTeamsRpt ONvw_Referrals_Grouped.OfficerID = dbo.MyTeamsRpt.OfficerIdLEFT OUTER JOIN dbo.vw_Officers ON vw_Referrals_Grouped.OfficerID =dbo.vw_Officers.OfficerIDWHERE (ReferralID>0) AND (MyTeamID = @TeamID) AND ((StartDateBETWEEN @FromDate-365 AND @ToDate-365) OR (StartDate BETWEEN @FromDateAND @ToDate))GROUP BY TeamName, OffAffiliateDesc, OffLocationDesc, OfficerName,ActiveHAVING Sum(CASE WHEN StartDate BETWEEN @FromDate AND @ToDate THEN 1ELSE 0 END)>0 Or Active = 1ORDER BY TeamName, OffAffiliateDesc, OffLocationDesc, OfficerName,ActiveENDIF @Mode = 'RM'BEGINIF @BUnitId 0BEGINSELECT OffAffiliateDesc, OffLocationDesc, OfficerName, Active, ''As TeamName, OffBUnitDesc As BUnit,Sum(CASE WHEN StartDate BETWEEN @FromDate AND @ToDate THEN 1 ELSE 0END) As CurrYr,Sum(CASE WHEN StartDate BETWEEN @FromDate-365 AND @ToDate-365 THEN 1ELSE 0 END) As PrevYr,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 1037) AND ((OutcomeId IS NULL) OR (OutcomeID =0)) AND(DATEDIFF(dd,StartDate,@ToDate) * -1 <-30) THEN 1 ELSE 0 END) AsPastDue,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 1037) THEN 1 ELSE 0 END) As Ref,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 63) THEN 1 ELSE 0 END) As CallSched,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 64) THEN 1 ELSE 0 END) As PropPres,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 65) THEN 1 ELSE 0 END) As PropAcc,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 66) THEN 1 ELSE 0 END) As BremApp,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 67) THEN 1 ELSE 0 END) As BusBook,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeId = 106) THEN 1 ELSE 0 END) As NonQual,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeId = 992) THEN 0 ELSE 0 END) As Duplicate,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeID = 107) THEN 1 ELSE 0 END) As OutdatedFROM vw_Referrals_GroupedLEFT OUTER JOIN dbo.vw_Officers ON vw_Referrals_Grouped.OfficerID =dbo.vw_Officers.OfficerIDWHERE (ReferralID>0) AND (vw_Referrals_Grouped.OfficerID = @UserID)AND ((StartDate BETWEEN @FromDate-365 AND @ToDate-365) OR (StartDateBETWEEN @FromDate AND @ToDate)) AND OffBUnitID = @BUnitIDGROUP BY OffBUnitDesc, OffAffiliateDesc, OffLocationDesc,OfficerName, ActiveHAVING Sum(CASE WHEN StartDate BETWEEN @FromDate AND @ToDate THEN 1ELSE 0 END)>0 Or Active = 1ORDER BY OffBUnitDesc, OffAffiliateDesc, OffLocationDesc,OfficerName, ActiveEND--ELSEIF @BUnitId = 0BEGINSELECT OffAffiliateDesc, OffLocationDesc, OfficerName, Active, ''As TeamName, '' As BUnit,Sum(CASE WHEN StartDate BETWEEN @FromDate AND @ToDate THEN 1 ELSE 0END) As CurrYr,Sum(CASE WHEN StartDate BETWEEN @FromDate-365 AND @ToDate-365 THEN 1ELSE 0 END) As PrevYr,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 1037) AND ((OutcomeId IS NULL) OR (OutcomeID =0)) AND(DATEDIFF(dd,StartDate,@ToDate) * -1 <-30) THEN 1 ELSE 0 END) AsPastDue,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 1037) THEN 1 ELSE 0 END) As Ref,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 63) THEN 1 ELSE 0 END) As CallSched,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 64) THEN 1 ELSE 0 END) As PropPres,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 65) THEN 1 ELSE 0 END) As PropAcc,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 66) THEN 1 ELSE 0 END) As BremApp,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND (StageId= 67) THEN 1 ELSE 0 END) As BusBook,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeId = 106) THEN 1 ELSE 0 END) As NonQual,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeId = 992) THEN 0 ELSE 0 END) As Duplicate,Sum(CASE WHEN (StartDate BETWEEN @FromDate AND @ToDate) AND(OutcomeID = 107) THEN 1 ELSE 0 END) As OutdatedFROM vw_Referrals_GroupedLEFT OUTER JOIN dbo.vw_Officers ON vw_Referrals_Grouped.OfficerID =dbo.vw_Officers.OfficerIDWHERE (ReferralID>0) AND (vw_Referrals_Grouped.OfficerID = @UserID)AND ((StartDate BETWEEN @FromDate-365 AND @ToDate-365) OR (StartDateBETWEEN @FromDate AND @ToDate))GROUP BY OffAffiliateDesc, OffLocationDesc, OfficerName, ActiveHAVING Sum(CASE WHEN StartDate BETWEEN @FromDate AND @ToDate THEN 1ELSE 0 END)>0 Or Active = 1ORDER BY OffAffiliateDesc, OffLocationDesc, OfficerName, ActiveENDENDEND

View 3 Replies View Related

Why Does A Query Runs Considerably Faster Than Stored Procedure?

Dec 29, 2003

I have an stored procedure that takes 23 seconds to execute. However, the same query is executed in 4 seconds.

All the tests where made using the Query Analizer.

What could be wrong?

Thanks a lot in advance.

View 13 Replies View Related

ASP Cannot Run Stored Proc Until The Web User Has Run The Proc In Query Analyzer

Feb 23, 2007

I have an ASP that has been working fine for several months, but itsuddenly broke. I wonder if windows update has installed some securitypatch that is causing it.The problem is that I am calling a stored procedure via an ASP(classic, not .NET) , but nothing happens. The procedure doesn't work,and I don't get any error messages.I've tried dropping and re-creating the user and permissions, to noavail. If it was a permissions problem, there would be an errormessage. I trace the calls in Profiler, and it has no complaints. Thedatabase is getting the stored proc call.I finally got it to work again, but this is not a viable solution forour production environment:1. response.write the SQL call to the stored procedure from the ASPand copy the text to the clipboard.2. log in to QueryAnalyzer using the same user as used by the ASP.3. paste and run the SQL call to the stored proc in query analyzer.After I have done this, it not only works in Query Analyzer, but thenthe ASP works too. It continues to work, even after I reboot themachine. This is truly bizzare and has us stumped. My hunch is thatwindows update installed something that has created this issue, but Ihave not been able to track it down.

View 1 Replies View Related

Adhoc Query Tool For Sql Server ???

Oct 31, 2005

Hi !!We are developing an application where we need a Query tool which allows customer to do Ad-Hoc or random query.. something similar to lets say http://salebyowner.com/advancedSearch.phpWe have few more options than this on which customer can do search. I don't think dynamic query in C# code or something like that is going to help me. Am I right? Do we have to use any type of query tool or something for doing this?

View 6 Replies View Related

Adhoc Query In Sql Reporting Service

May 6, 2008

Hi,
Using Reporting Service 2005, I want to give User an Interface where user can directly paste sql query like -
select * from employee.
and corrosponding data will be displayed to user.
Is there are any way?
Thanks,
Ashwin

View 6 Replies View Related

Stored Proc. Query Help

Feb 7, 2006

I have two tables, Employee and EmployeeEval, and need to try and Select the LastName, FirstName, EmployeeID, and DeptID from the Employee Table where there is no record of that employee in the EmployeeEval Table. I tried this and it won't work, I should get back like 80 employees when the query is written correctly:
select e.deptid, (e.lastname + ', ' + e.firstname) as EmpName, e.employeeid from employee e INNER JOIN employeeeval ev ONe.employeeid <> ev.employeeid where periodid = 176 and e.companyid = '21' and e.FacilityID = '01'

View 3 Replies View Related

Stored Proc In Query

May 11, 2004

Hi

I would like to write a query, where I would like to pass in a string value into proc, which is comma delimited, ie

create proc spName
@list as varchar(4000)
as
....
....
....


Then I wish to iterate through the string running a query for each item in the list.

Do I place values in @list into a cursor ?

View 3 Replies View Related

Can You Trace Into A Stored Proc? Also Does RAISERROR Terminate The Stored Proc Execution.

Feb 13, 2008

I am working with a large application and am trying to track down a bug. I believe an error that occurs in the stored procedure isbubbling back up to the application and is causing the application not to run. Don't ask why, but we do not have some of the sourcecode that was used to build the application, so I am not able to trace into the code.
So basically I want to examine the stored procedure. If I run the stored procedure through Query Analyzer, I get the following error message:
Msg 2758, Level 16, State 1, Procedure GetPortalSettings, Line 74RAISERROR could not locate entry for error 60002 in sysmessages.
(1 row(s) affected)
(1 row(s) affected)
I don't know if the error message is sufficient enough to cause the application from not running? Does anyone know? If the RAISERROR occursmdiway through the stored procedure, does the stored procedure terminate execution?
Also, Is there a way to trace into a stored procedure through Query Analyzer?
-------------------------------------------As a side note, below is a small portion of my stored proc where the error is being raised:
SELECT  @PortalPermissionValue = isnull(max(PermissionValue),0)FROM Permission, PermissionType, #GroupsWHERE Permission.ResourceId = @PortalIdAND  Permission.PartyId = #Groups.PartyIdAND Permission.PermissionTypeId = PermissionType.PermissionTypeId
IF @PortalPermissionValue = 0BEGIN RAISERROR (60002, 16, 1) return -3END 
 

View 3 Replies View Related

How To Construct The Query In Stored Proc

Jun 20, 2005

Hi,In the past I build up the query string within VB.NET page and easy to add the filtering statements in the SQL statement since it is just a string. For example, if user selected an option then include it in the filter, otherwise, just return all rows from table:Codes in ASPX.VB:   Dim SQL as String="SELECT * From Table1"   IF UserOption <> Null then      SQL = SQL & " WHERE Column1=" UserOption"   End ifNow, since I have a complicated page which need to use Stored Procedure to manapulate a temporary table before the final result. But I found when I want to add some user options similar to above, I found I don't know how to do it in Stored Procedure. In the Stored Procedure Property screen, I can't insert a IF..THEN statement within a SELECT statement. Seems I can only check the user option first and then determine the SELECT statement to use. That is: IF UserOption THEN SELECT statement 1 ELSE SELECT statement 2.But it is impossible for me to do this way since I'm not only one user option on the page. User usually can have several filters/selections on his screen. So if check which user option(s) are selected and write a static SELECT statement for it, I will have to program a complicated store procedure to cater all combinations for all user options (where some options may be null).Hope you can understanding what my mean and give me advices.Regards,Raymond

View 8 Replies View Related

Returning A Value From Stored Proc With Query

Jul 18, 2014

In some of our business object reports we have to create variables to decode values to what we want. I am trying to replicate this in SQL Server and remember doing this in SQL server 2000 years ago back can't remember the exact way to do it. I remember running a query and calling stored proc within query which would return the value I wanted but not sure if I can still do this in SQL server 2008 and by that I mean doing it within query or have to do it another way.

Basically what I want is to have a procedure with all the variables replicated within that procedure so that when I run a query I can just call the appropriate bit of code by passing a specific name like

select job.dept, dbo.decodevariable('ShowJobDesc' job.jobtitle), job.salary
from job

so 'ShowJobDesc' and the job.jobtitle would be used to decode each job title to return job description.Just a bit unsure and can't remember if I am doing this the right way, is this possible?

View 2 Replies View Related

Query Takes For Every When Run In A Stored Proc

Mar 17, 2006

Hello,

When I run the SQL statements piece by piece, the execution time under 10 seconds. The stored proc takes forever.

All I am doing is retrieving (10,000+) rows of data using temp tables and joins. I have indexed each of the temp table.

What could be the reason for the slowness?

Thanks in advance!!!
sqlnovice123

View 4 Replies View Related

Query Function In Stored Proc... How To Do It??

May 10, 2007

how can i view all the records in my stored procedure???



how is the query function done??



for example i had my datagrid view... and of course a view button that will trigger a view action in able to view the entire records that i input....



i am not familiar with such things..



pls help me to figure this out..



thanks..



im just a begginer when it comes to this..



pls help me..



thanks..



View 1 Replies View Related

Sql Stored Procedure - Proc Creates Query

Jan 11, 2007

Is it possible to pass 5 variables to a proc and have IT do the thinking and query structuring?
An example of what I'm try to do is have one proc for getting vehicles by make, model, and years
example of what I'd like to accomplish:veh_list_vehicleInfo_byDetails
@TypeID int,
@MakeID int,
@ModelID int,
@begYear int,
@endYear int
AS
BEGIN

declare @SQL as nvarchar(500)
set @SQL = 'SELECT a.ID, b.Model, c.Make, d.Name, a.Year, a.Mileage, a.Price, a.Sale, a.Certified_Pre_Owned FROM veh_vehicles a INNER JOIN veh_model b ON a.ModelID = b.ID INNER JOIN veh_make c ON a.MakeID = c.ID INNER JOIN veh_location d ON a.LocationID = d.ID'

decalre @ATTRIBUTES as nvarchar(500)
if @TypeID is not null AND @TypeID > 0
begin
set @ATTRIBUTES = @ATTRIBUTES + ' a.TypeID = ' + @TypeID
end
if @MakeID is not null AND @MakeID > 0
begin
set @ATTRIBUTES = @ATTRIBUTES + ' a.MakeID = ' + @MakeID
end

....etc etc.......

if Len(@ATTRIBUTES) > 0
begin
EXEC(@SQL + ' WHERE ' + @ATTRIBUTES)
End
Else
BEGIN
EXEC(@SQL)
END

END
 But I keep getting some errors regarding converting 'a.TypeID = ' to int
?????  Please help!!
 I figured this would be easier than writing stored procs for EACH situation

View 2 Replies View Related

Building A Query In A Stored Proc With String

Feb 27, 2008

This should be an easy enough answer to find if I just knew what to search on!

I am building a query within my stored procedure based on what parameters are passed in. For example, suppose I have a table with first name and last name. I can call the sp with either first name or last name or both, so I build a query accordingly that says:
select * from tblNames where FirstName = 'Hannah'
or
select * from tblNames where LastName = 'Montana'
or
select * from tblNames where FirstName = 'Hannah' and LastName='Montana'

My problem is putting the single quotes around the variable value.
SELECT @whereClause = @whereClause + ' AND tblNames.LastName=' @LastName-with-singlequotes-around-it

Thanks

View 3 Replies View Related

I Can't Find My Stored Proc In Query Analyser

Jun 4, 2006

1/
I create stored procedure in Query Analyser using:
ALTER PROCEDURE dbo.unshippedtotal
@name char,
@ytd int output
AS
select * from vwaccount
select @ytd=sum(AccAccnnmb) from vwaccount
return
GO

But When I try to expand the list of stored procedures under the DB and the server name, I can t see my Stored Proc called "unshippedtotal"

Any ideas

2/ Another question pls:
Can we use Query Analyser to do the same tasks we do with Entreprise Manager like creating and modifying tables, Creating Stored Procedures, Modifying Views... (I m more familiar with Entreprise Manager but somebody told me it s better to use Query Analyser)

Thanks for coaching :)

View 9 Replies View Related

Stored Proc: Query Vals To Local Variables

Aug 18, 2004

I am brand spankin new to stored procedures and don't even know if what I want to do is possible. From everything I've read it seems like it will be. I have a table, punchcards. In this table are all the punch in/out times for a week. I want to create a stored proc to calculate how many hours a punchcard entry is.

Thats the dream.

The reality is that I can't even get a tinyint from a table to load to a variable and be printed out. I am using sql server 8.

Here is what I have as of this moment for my sp.


ALTER PROCEDURE usp_CalculatePunchcard
AS
DECLARE @dtPP DateTime
SET @dtPP = (SELECT thursday_in1
FROM punchcards
WHERE (punchcard_id = 1))
/*
Also tried....
SELECT @dtPP=thursday_in1
FROM punchcards
WHERE (punchcard_id = 1)
*/

PRINT @dtPP

RETURN
/*
for some reason i can't use GO ... even though every
document i've read on stored procedures has used GO
and none use RETURN
*/


The only output this is producing is ' Running dbo."usp_CalculatePunchcard". '

Any help would be greatly appreciated as I am about to kick someone/something.

Thanks

View 2 Replies View Related

Select Query From A Stored Proc When The Values Can Be Blank.

Oct 10, 2006

Hi All,

I think what am trying to do is quite basic.

I have 3 paramaters@value1, @value2,@value3 being passed into a stored
proc and each of these parameters can be blank. If one of them is blank
and the rest of them have some valid values, then I should just exclude
the column check for the value that is blank.

For e.g if all my parameters being passed are non- empty then I would
do this
select * from tblName
where column1 like @value1 and column2 like @value2 and column3 like
@value3

else if I have one of the parameter being passed as empty, I should
ignore that parameter like
if@value1 is empty then my sql should be

select * from tblName
where column2 like @value2 and column3 like @value3

I don't want to do a dyanmic sql because of rights and security issue.
I want it through a stored procedure only.

Also, all the three columns can have null values in the table.
Please let me know what is the best possible way to do this. Thanks in
advance !.

.noscripthide
{display:none;}
.noscriptinline
{display:inline;}
.noscriptblock
{display:block;}

.scripthide
{display:none;}
.scriptinline
{display:inline;}
.scriptblock
{display:block;}

.script12hide
{display:none;}
.script12inline
{display:inline;}
.script12block
{display:block;}
.lnav
{position:absolute;}
.lnavch
{margin-left:23.0ex;}

.script13hide
{display:none;}
.script13inline
{display:inline;}
.script13block
{display:block;}

.hide
{display:none;}
.hide_ie
{;}
.hide_ie
{display:none;}
img
{border:0;}
img
{border-color:#0000a0;}
input.ck
{margin-left:-2px;}
input.bt, button.bt
{padding:0 .4em 0 .4em;width:auto;overflow:visible;}
input.bt, button.bt
{width:1px;}
.fixed_width
{font-family:fixed-width, monospace;font-size:90%;}
a:visited
{color:#551a8b;}
a:active
{color:#f00;}
.inheritcolor a
{color:inherit;}
.minmaxwie
{width:100%;}
* html .minmaxwie
{;}
.fl:visited
{color:#551a8b;}
.fl:active
{color:#f00;}
.fl:link
{color:#7777CC;}
.z
{display:none;}
.on:active
{color:#f00000;}
.don:active
{color:#f00000;}
.mbody
{margin-top:4px;}
body,td,input,textarea,select
{font-family:arial,sans-serif;}
body,td
{font-size:83%;}
input,textarea,select
{font-size:100%;}
form
{margin:0;}
.tick
{font-family:webdings;text-decoration:none !important;}
.qr
{width:100%;padding:4px;font-family:arial,sans-serif;}
.nu
{text-decoration:none;}
.gt
{border-collapse:collapse;}
.gt td
{padding:.3em 4px;border-right:1px solid #ffcc33;}
.gm td
{padding:.3em 1em .3em 0px;}
.bnk
{border:1px solid #ffcc33;}
.bnk td
{border-right-width:0px !important;}
.sel td.seltd
{padding:4px 4px 4px 4px;border:1px solid #ffcc33;border-right:none;font-weight:bold;}
p.b
{margin-bottom:1.5em;margin-top:.3em;}
.adb, .adbrnav
{border-left:1px solid #fff4c2;}
.msgdate
{color:#676767;}
.md
{color:#555555;}
.st
{margin-left:-1px;}
.nb
{white-space:nowrap;}
.np
{padding:0px;}
.p
{font-weight:bold;}
.mo
{margin:.5em 0 0 0;}
.oa
{padding:2px .5em;}
.sbox
{margin-top:1em;margin-bottom:1em;}
button a:link
{text-decoration:none;color:black;}
button a:hover
{text-decoration:none;color:black;}
.b
{font-weight:bold;}
.fontsize0
{font-size:78%;}
.fontsize1
{font-size:87%;}
.fontsize2
{font-size:96%;}
.fontsize_25
{font-size:100%;}
.fontsize3
{font-size:108%;}
.fontsize4
{font-size:120%;}
.fontsize5
{font-size:133%;}
.fontsize6
{font-size:150%;}
.fontsize7
{font-size:150%;}
.cv
{width:100%;}
.lk
{color:#0000CC;text-decoration:underline;cursor:pointer;}
.nl
{padding:5px 0 2px 5px;}
.tsh
{border-top:1px solid #ffcc33;}
.tlsh
{border-top:1px solid #ffcc33;}
.blsh
{border-bottom:1px solid #ffcc33;}
.bsh
{border-bottom:1px solid #ffcc33;}
.lsh, .tlsh, .blsh
{border-left:1px solid #ffcc33;}
.lnav
{left:9px;width:23.0ex;overflow:hidden;}
.lnavch
{;}
.lnavi
{font-size:100%;}
.lnavim
{margin-left:-2px;}
* html .lnav
{left:11px;}
.alertboxout
{margin:5px 15px 0px 10px;clear:left;}
.alertboxin
{clear:left;color:black;background-color:#fad163;font-weight:bold;text-align:center;padding:0px 15px 0px 15px;position:relative;margin:-1px 0px;}
.ctl
{padding-left:2px;}
.mb
{padding:6px 8px 0 5px;}
.exh
{margin:0 0 0 5px;background-color:#e8e8e8;}
.exh div div
{padding-top:4px;}
.thread_star
{padding:0 0 4px 2px;}
* html .thread_star
{padding:0 0 0 2px;}
.blurb_star
{padding:0 0 0 2px;}
* html .blurb_star
{padding:2px 0 0 2px;}

View 7 Replies View Related

How To Debug SQL 2005 Stored Proc With No Query Analyzer

Aug 8, 2007

Hi,
In SQL 2000, to debug a stored proc I would launch QA, right click and hit debug.
How do I accomplish this with SQL 2005. I can't see that it came with QA.
Thank you,
Steve

View 1 Replies View Related

How To Return A Numeric Value Based Upon If A Record Is Returned From My Query/Stored Proc.

Oct 2, 2007

 
I need to call the stored procedure below. Basically what I need to know is if the query returns a record?
Note I would be happy if I could just return the number Zero if no records are returned. Can someone please help me out here?Here is my query so far in SQL Server. I just don't know how to return a value based upon the result of the records returned from the query.
GOCREATE PROCEDURE [dbo].[GetNameStatus]( @CountryId decimal, @NameId decimal, @DescriptionId decimal)AS SELECT     Name.Active FROM       Name INNER JOIN               NameDescription ON Name.NameId = NameDescription.NameId WHERE Name.CountryId=@CountryId AND               Name.NameId=@NameId AND NameDescription.DescriptionId=@DescriptionId AND Name.Active='Y'
 

View 3 Replies View Related

How Do Use Stored Proc Passing Parameter From Table In Selcet Query Statement

Aug 8, 2002

i want to use store procedure in select query statement. store procedure will take two parameters from table and return one parameter.

for example i want to use

select p1 = sp_diff d1,d2 from table1

sp_diff is stored procedure
d1,d2 value from table
p1 is the returning value

View 1 Replies View Related

Stored Proc - Calling A Remote Stored Proc

Aug 24, 2006

I am having trouble executing a stored procedure on a remote server. On my
local server, I have a linked server setup as follows:
Server1.abcd.myserver.comSQLServer2005,1563

This works fine on my local server:

Select * From [Server1.abcd.myserver.comSQLServer2005,1563].DatabaseName.dbo.TableName

This does not work (Attempting to execute a remote stored proc named 'Data_Add':

Exec [Server1.abcd.myserver.comSQLServer2005,1563].DatabaseName.Data_Add 1,'Hello Moto'

When I attempt to run the above, I get the following error:
Could not locate entry in sysdatabases for database 'Server1.abcd.myserver.comSQLServer2005,1563'.
No entry found with that name. Make sure that the name is entered correctly.

Could anyone shed some light on what I need to do to get this to work?

Thanks - Amos.

View 3 Replies View Related

Stored Proc Question : Why If Exisits...Drop...Create Proc?

Jun 15, 2006

Hi All,Quick question, I have always heard it best practice to check for exist, ifso, drop, then create the proc. I just wanted to know why that's a bestpractice. I am trying to put that theory in place at my work, but they areasking for a good reason to do this before actually implementing. All Icould think of was that so when you're creating a proc you won't get anerror if the procedure already exists, but doesn't it also have to do withCompilation and perhaps Execution. Does anyone have a good argument fordoing stored procs this way? All feedback is appreciated.TIA,~CK

View 3 Replies View Related

I Need A Faster Query

Jun 20, 2007

Hi y'all,
I've recently run a profiler on my code and following query took 7 seconds:
SELECT TOP 10 UI, COUNT(UI) AS Expr1 FROM table WHERE (UI <> 'custom_welcome') GROUP BY UI ORDER BY COUNT(UI) DESC
Is it possible to rewrite this so my code gets faster? It's also possible that it's due to the size of the table?
Thanks in advance! I'll let you know how long your query takes :)

View 4 Replies View Related

Faster SQL Query

Mar 31, 2004

Hi!
I M basically an application developer & use simple sql queries in my programmings. I do not have much idea abt tuning/auditing part & thatswhy i m unable to answer them properly in my interviews. Can anybody give me some tips?????

Question 1:
In a stored procedure, One SELECT stmt is there & depending upon the @rowcount, it updates around 14000 records which is also written inside this stored procedure. Instead of writing this way, there is some other way which is faster than this. Can anybody tell me the correct way???

Question 2:Can anybody give me few examples like this?????? I need them desparetly.

Thanx. Bye.

View 37 Replies View Related

How To Tell If One Query Is Faster Than Another

Jul 26, 2006

I have rewritten a stored procedure that consists of a single select that selects from a view. Essentially I combined the select in the view and the select in the sp into one select. I am now trying to determine if the new version is faster.

The estimated execution plan gives a ratio of 96% : 4% in favour of the new version when I run them together from a query window but when I try to time them I can't get a satisfactory result.

If I run each query once and display the difference between start and end time, they display 0. If I run each one 100, 200, etc times I get different results each time.

Is there anything I can do?

View 5 Replies View Related

Sp_executeSQL Perform Faster Than Stored Procedure, Why?

Dec 24, 2007



Hi,

I Have a stored procedure named pPatientFindByID that return one patient record from the Client.Patient table. The stored procedure has one parameter @patientID uniqueidentifier. i have set the NOCOUNT ON before running the SQL statement and making it OFF after it finishes execution. The table has a primary key ( clustered ) on patientID. The table has 66840 records in it. The index IS 0 (ZERO) percent fragmented and 3 level depth.

The stored proc returnes null or 1 record maximum. My problem is that the stored procedure takes about 2268 microsecond (2 millisecond) on average. while i execute the same SQL using sp_executeSQL it takes about 710 microsecond (< 1 millisecond). That is 3 time faster than stored procedure.

The SET OPTION are same for both the statement.

To troubleshoot the problem i have enabled the trace and captured the events. there were no recompile for both the stored proc and sp_executeSQL and not even the statement level recompilation.

I am trying to figure out why my stored procedure is taking longer than sp_executesql. Both the (stored proc and sp_executeSQL) has the same execution plan.


This is affecting our application performance. Does anyone know about this or have experience the same problem ever? your help would be greatly appriciated.

Data


1. Stored Procedure


/****** Object: StoredProcedure [dbo].[pPatientFindByID] Script Date: 12/24/2007 11:19:58 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE PROCEDURE [dbo].[pPatientFindByID]

@patientID uniqueidentifier

WITH EXECUTE AS OWNER

AS

BEGIN

SET NOCOUNT ON



SELECT

[patient].[AVINumber] AS 'AVINumber',

[patient].[BirthDate] AS 'BirthDate',

[patient].[BreedID] AS 'BreedID',

[patient].[ChangeDate] AS 'ChangeDate',

[patient].[ChangeWorkstationID] AS 'ChangeWorkstationID',

[patient].[ClientID] AS 'ClientID',

[patient].[Color] AS 'Color',

[patient].[County] AS 'County',

[patient].[CountyRabiesTagNumber] AS 'CountyRabiesTagNumber',

[patient].[CreateDate] AS 'CreateDate',

[patient].[CreateWorkstationID] AS 'CreateWorkstationID',

[patient].[DeathDate] AS 'DeathDate',

[patient].[DeathReasonCode] AS 'DeathReasonCode',

[patient].[FirstVisitDate] AS 'FirstVisitDate',

[patient].[HasAllergy] AS 'HasAllergy',

[patient].[HasBitesOrScratch] AS 'HasBitesOrScratch',

[patient].[HasChronicCondition] AS 'HasChronicCondition',

[patient].[HasDeclinedPreventiveCare] AS 'HasDeclinedPreventiveCare',

[patient].[HasMedicalAllergy] AS 'HasMedicalAllergy',

[patient].[HospitalID] AS 'HospitalID',

[patient].[IsBites] AS 'IsBites',

[patient].[IsBitesInFear] AS 'IsBitesInFear',

[patient].[IsClinicalStudy] AS 'IsClinicalStudy',

[patient].[IsLitters] AS 'IsLitters',

[patient].[IsMixBreed] AS 'IsMixBreed',

[patient].[IsScratches] AS 'IsScratches',

[patient].[LastVisitDate] AS 'LastVisitDate',

[patient].[ManufacturerNameOfAVIChip] AS 'ManufacturerNameOfAVIChip',

[patient].[ManufacturerNameOfMicrochip] AS 'ManufacturerNameOfMicrochip',

[patient].[MicrochipNumber] AS 'MicrochipNumber',

[patient].[Name] AS 'Name',

[patient].[Note] AS 'Note',

[patient].[PatientID] AS 'PatientID',

[patient].[RabiesTagNumber] AS 'RabiesTagNumber',

[patient].[SexCode] AS 'SexCode',

[patient].[SpeciesID] AS 'SpeciesID',

[patient].[Status] AS 'Status',

[patient].[SystemLog] AS 'SystemLog',

[patient].[Weight] AS 'Weight',

[patient].[WellnessplanLevel] AS 'WellnessplanLevel',

[patient].[WellnessplanValue] AS 'WellnessplanValue'

FROM

[Client].[Patient] [patient]

WHERE

[PatientID] = @patientID

SET NOCOUNT OFF

END


2. sp_executeSQL


set nocount on

execute

sp_executeSQL N'

SELECT [patient].[AVINumber]

,[patient].[BirthDate]

,[patient].[BreedID]

, [patient].[ChangeDate]

, [patient].[ChangeWorkstationID]

, [patient].[ClientID]

, [patient].[Color]

, [patient].[County]

, [patient].[CountyRabiesTagNumber]

, [patient].[CreateDate]

, [patient].[CreateWorkstationID]

, [patient].[DeathDate]

, [patient].[DeathReasonCode]

, [patient].[FirstVisitDate]

, [patient].[HasAllergy]

, [patient].[HasBitesOrScratch]

, [patient].[HasChronicCondition]

, [patient].[HasDeclinedPreventiveCare]

, [patient].[HasMedicalAllergy]

, [patient].[HospitalID]

, [patient].[IsBites]

, [patient].[IsBitesInFear]

, [patient].[IsClinicalStudy]

, [patient].[IsLitters]

, [patient].[IsMixBreed]

, [patient].[IsScratches]

, [patient].[LastVisitDate]

, [patient].[ManufacturerNameOfAVIChip]

, [patient].[ManufacturerNameOfMicrochip]

, [patient].[MicrochipNumber]

, [patient].[Name]

, [patient].[Note]

, [patient].[PatientID]

, [patient].[RabiesTagNumber]

, [patient].[SexCode]

, [patient].[SpeciesID]

, [patient].[Status]

, [patient].[SystemLog]

, [patient].[Weight]

, [patient].[WellnessplanLevel]

, [patient].[WellnessplanValue]

FROM [Client].[Patient] [patient] WHERE [PatientID] = @patientID

',N'@patientID uniqueidentifier'

,'B1ABC1EA-D4AB-DB11-921E-00087434402F'





set nocount off

3- Trace Data



Name Event TextData Duration
SQL:BatchCompleted 12 exec dbo.pPatientFindByID @patientID='B1ABC1EA-D4AB-DB11-921E- 00087434402F' 2268
SQL:BatchCompleted 12 set nocount on execute sp_executeSQL N' SELECT [patient].[AVINumber] 710





DBA

View 8 Replies View Related

Faster Query Results

Oct 17, 2007

Can anyone give me the basics of speeding up reports that use queries or views or nested views?
Current reports are now taking over 2 minutes to show.We have thousands and sometimes even millions of records to report against.Queries have 4 and 5 table joins etc.
We are using ASP.NET 2.0 in Visual Studio 2005 and Crystal Reports.
Thanks
 

View 4 Replies View Related

Help Make Query Run Better (faster)

Mar 20, 2007

I need help makeing the following query run more efficently.


Code:


SELECT t1.ID,t1.firstName,t1.lastName,t1.address,t1.city,t1.state, t1.zip,t1.locationAddress,t1.locationCity,t1.locationState,t1.locationZip
FROM Landlord_tbl t1
left outer join Mail_tbl t2
ON t2.potentialSitesID = t1.potentialSitesID
WHERE t2.mailed_out_date is null and NOT(t1.firstName+t1.lastName) is Null
GROUP BY t1.ID,t1.firstName,t1.lastName,t1.address,t1.city,t1.state, t1.zip,t1.locationAddress,t1.locationCity,t1.locationState,t1.locationZip
ORDER BY t1.firstName, t1.lastName, t1.city, t1.state

View 3 Replies View Related

Query Run Time (which Should Be Faster?)

Feb 28, 2008

Hi, when I execute the sql in DBTestArchive and then DBTest query analyzer , I found that the run time is shorter in DBTest. Can I make assumption that the query run time is shorter in DBTest if I select data from it and insert into another database? Thanks.



INSERT INTO DBTestArchive.dbo.tblVendorMasterArchive
SELECT * FROM DBTest.dbo.tblVendorMaster

View 1 Replies View Related

Better (faster) Way Of Handling Query

Mar 26, 2008



I have a query which will display the employee name who is handling maximum number of project.
the query is



Code Snippet

select EmployeeDetails.Empid,

EmployeeDetails.FirstName + ' '+EmployeeDetails.LastName as EmpName,

count(*) as Number_Of_Projects
from EmployeeDetails left outer join LUP_EmpProject

on EmployeeDetails.Empid= LUP_EmpProject.Empid
group by EmployeeDetails.Empid,EmployeeDetails.FirstName,EmployeeDetails.LastName
HAVING count(*)=(SELECT TOP 1 COUNT(EmpID)



FROM LUP_EmpProject GROUP BY EmpID ORDER BY 1 DESC)






where EmployeeDetails table contain empname and empid. LUP_EmpProject table contain empid and project id.

Can anybody help me in writing a better query than the above given?

Please help!!!!!!!!!!

View 4 Replies View Related







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