Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Stored Procedure is very slow

$
0
0

I have a stored procedure that is very slow and would like more efficient SQL.  I want to get a selection of data put into a @SearchTbl that I send elsewhere for further manipulation.  I do these in two parts.  First, if the sending program sends a specific @UserName, @EntryTime, and/or @Type, I get all entries that meet these conditions.  If the user does not send an entrytime (If NULL), I get the latest entries from the @SearchTbl for each unique combination of certain variables.  Is there a way to do both in one step?

Any suggestions on how to make these steps below faster?

CREATE PROCEDURE MyProcedure             
 @UserName nvarchar(255) = NULL, @EntryTime datetime = NULL, @Type nvarchar(255) = NULL
AS
DECLARE @SQL nvarchar(4000)
DECLARE @whereAdd nvarchar(4000)
DECLARE @SearchTbl tempSearchTbl_tbltype
DECLARE @TvuTbl TVU_tbltype
DECLARE @t int
DECLARE @tempCt int
DECLARE @narCt int
DECLARE @n int

IF @Type IS NOT NULL AND @UserName IS NOT NULL
BEGIN
   SET @whereAdd = ' WHERE Type = @Type AND UserName = @UserName'
END
          
IF @Type IS NOT NULL AND @UserName IS NULL
BEGIN
  SET @whereAdd = ' WHERE Type = @Type'
END

IF @Type IS NULL AND @UserName IS NOT NULL
    BEGIN
      	SET @whereAdd = ' WHERE UserName = @UserName'
     END
SET @SQL = 'SELECT CName, UserName, Type, Address, CardNum, CText, 
EntryTime, Var1, Var2, Var3 FROM PTable' + @whereAdd

IF @Type IS NULL AND @UserName IS NULL
BEGIN
   SET @SQL = 'SELECT CName, UserName, Type, Address, CardNum, CText, 
 EntryTime, Var1, Var2, Var3 FROM PTable'
END
INSERT INTO @SearchTbl (CName, UserName, Type, Address, CardNum, CText, 
EntryTime, Var1, Var2, Var3)
EXEC sp_executesql @SQL,
N'@UserName nvarchar(255), @Type nvarchar(255)'
@UserName, @Type

GetLatestLoop:
IF @EntryTime IS NULL
 BEGIN
With CTE As (SELECT CName, Type, CText, CardNum,
    Row_Number() OVER(Partition By CName, Type, CardNum, Type ORDER BY EntryTime Desc) AS rn
FROM @SearchTbl)
DELETE FROM CTE WHERE rn > 1
END


Gina






Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>